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,
While I agree that Graeme Blackwood's should be the accepted answer, because it practically solves the issue, it should be noted that a fixed element can be positioned relatively to its container.
I noticed by accident that when applying
-webkit-transform: translateZ(0);
to the body, it made a fixed child relative to it (instead of the viewport). So my fixed elements left
and top
properties were now relative to the container.
So I did some research, and found that the issue was already been covered by Eric Meyer and even if it felt like a "trick", turns out that this is part of the specifications:
For elements whose layout is governed by the CSS box model, any value other than none for the transform results in the creation of both a stacking context and a containing block. The object acts as a containing block for fixed positioned descendants.
http://www.w3.org/TR/css3-transforms/
So, if you apply any transformation to a parent element, it will become the containing block.
The problem is that the implementation seems buggy/creative, because the elements also stop behaving as fixed (even if this bit doesn't seem to be part of specification).
The same behavior will be found in Safari, Chrome and Firefox, but not in IE11 (where the fixed element will still remain fixed).
Another interesting (undocumented) thing is that when a fixed element is contained inside a transformed element, while its top
and left
properties will now be related to the container, respecting the box-sizing
property, its scrolling context will extend over the border of the element, as if box-sizing was set to border-box
. For some creative out there, this could possibly become a plaything :)
TEST