Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute positioning with percentages giving unexpected results

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?

like image 971
Jeroen Avatar asked Feb 22 '12 23:02

Jeroen


People also ask

When would you want to use absolute positioning?

When you need something to be positioned in an very specific spot you would use absolute positioning. For instance you may want to have an image with an overlapping caption that always sits at the top of the picture (say 20px from the top).

What does absolute positioning effect?

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

What does absolute positioning mean?

Absolute positioning defines the position of a given bounding box from the top and left side margins of the web page. This not only allows objects to be placed in an exact location, it also allows objects to be placed one on top of another.


1 Answers

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"

like image 127
animuson Avatar answered Sep 21 '22 23:09

animuson