I am trying to implement a fixed sidebar for a table of contents (TOC) on a website (i.e. one that stays in the same place as the user scrolls up/down).
I'm doing so using the following code in HTML:
and in CSS:
My attempt was inspired by the following tutorial:
Anyone know how I can fix/resolve this such that the table of content behaves properly when zooming?
CodePudding user response:
Handle max-width
Try setting a max-width
for your sidebar using vw
(viewport width).
This unit is not affected by the zoom variation. (as %
, vh
, vmin
, vmax
, and others)
This way, you can keep setting your Sidebar width in
px
or whatever CSS unit you need, but limiting the max value, based on the absolute screen width.
For example
width: 100px; // Your default width
max-width: 25vw; // Max absolute width (not affected by zoom)
// The zoom changes the element width
// but will never be larger than the 25% of your screen width (25vw)
Of course, you can also specify different
max-width
values for different screen sizes using some media queries.
If instead you prefer that the width of your Sidebar is of a constant width (in screen percentage), you can usevw
directly in yourwidth
(without the need for amax-width
).
Generally
Keep in mind which CSS units are affected by the zoom when you choose one.
CodePudding user response:
A fixed position element does not affect the position of other elements:
The element is removed from the normal document flow, and no space is created for the element in the page layout.
-- https://developer.mozilla.org/en-US/docs/Web/CSS/position#fixed
To overcome this behavior you simply need to set the div.contents
's padding-left
equal to whatever value is set for the width
of div.toc
. It looks like you are familiar with CSS variables, and I suggest using one in this case.
body {
--toc-width: 30vw;
--toc-background: red;
}
div.contents {
/* offset contents by toc width */
padding-left: var(--toc-width);
}
div.toc {
position: fixed;
top: 0;
left: 0;
bottom: 0;
width: var(--toc-width);
background-color: var(--toc-background);
}
<div >
<div ></div>
<h1>not toc</h1>
</div>
CodePudding user response:
You probably want to use percentage width here. Example:
div.toc {
position: fixed;
height: 100%;
width: 15%;
...
}
Zooming in modifies px
, em
and rem
values, but percentages are always the same.