I am trying to fix a div
so it always sticks to the top of the screen, using:
position: fixed;
top: 0px;
right: 0px;
However,
See this jsFiddle example. Resize and see how the fixed elements even move with the floated elements they are in. Use the inner-most scroll bar to see how the scroll would work on a site (fixed elements staying fixed).
As many here have stated, one key is not setting any positional settings on the fixed
element (no top
, right
, bottom
, or left
values).
Rather, we put all the fixed elements (note how the last box has four of them) first in the box they are to be positioned off of, like so:
Test
Some other content in.
Then we use margin-top
and margin-left
to "move" them in relation to their container, something like as this CSS does:
.fixed {
position: fixed;
margin-top: 200px; /* Push/pull it up/down */
margin-left: 200px; /* Push/pull it right/left */
}
Note that because fixed
elements ignore all other layout elements, the final container in our fiddle can have multiple fixed
elements, and still have all those elements related to the top left corner. But this is only true if they are all placed first in the container, as this comparison fiddle shows that if dispersed within the container content, positioning becomes unreliable.
Whether the wrapper is static, relative, or absolute in positioning, it does not matter.