Absolute positioning with percentages giving unexpected results
Solution 1
The absolute positioning is applied relative to the next parent element whose position is not static. In your case, that's the full page. Try setting position: relative
on the container division.
See the jsFiddle.
See: W3C - 10.1 - Definition of "containing block"
Solution 2
add
position:relative;
to container div .
Jeroen
Software developer, gamer, chef, and Stack Overflow fan from the Netherlands. Find me online in these places: 🌍 www.jeroenheijmans.nl 🐦 Twitter (@jeroenheijmans) 💼 LinkedIn 🍕 Meetup
Updated on July 05, 2022Comments
-
Jeroen almost 2 years
Please consider this jsfiddle, containing this html code:
<div id="container"> <div id="item">TEST</div> </div>
And some CSS:
#container { border: 1px solid red; height: 100px; width: 100px; } #item { border: 1px dashed purple; position: absolute; left: 50%; }
The results surprise me. Looking at the W3 positioning props I'd expect the
#item
to have its left value at 50% of the "containing block": the#container
. However, it seems to be at 50% of the entire page, not just the containing block. Even more surprising: if I tell the overflow of the container to stay hidden the "TEST" will still be there.All major browsers (including IE9) seem to exhibit the same behavior, so my expectations are probably incorrect. The question then is: what part of the spec explains this behavior, if any?
-
animuson over 12 yearsThat is
position: fixed
, which always uses the full page container. Absolute positioning does apply to its parent elements, see my answer. -
thepriebe over 12 yearsToo true. I fully agree. Thanks.
-
viery365 about 6 yearsYeah, but if there are no ancestors relatively positioned, the answer is at least partially correct with an extra point because the other answers don't really reply to the question. Absolute position can be used with static ancestors. Its behaviour is a similar with fixed, the difference is that when you scroll down and up the page, the absolute positioned element with static ancestors goes along with the page. stackoverflow.com/a/13239575/4551792