Jeroen
Jeroen

Reputation: 63699

Absolute positioning with percentages giving unexpected results

Please consider this HTML and CSS snippet:

#container {
  border: 1px solid red;
  height: 100px;
  width: 100px;
}

#item {
  border: 1px dashed purple;
  position: absolute;
  left: 50%;
}
<div id="container">
  <div id="item">TEST</div>
</div>

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?

Upvotes: 19

Views: 36586

Answers (2)

animuson
animuson

Reputation: 54719

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"

Upvotes: 37

mohsen dorparasti
mohsen dorparasti

Reputation: 8405

add

position:relative; 

to container div .

Upvotes: 2

Related Questions