Absolute positioning with percentages giving unexpected results

大憨熊 提交于 2019-12-03 16:20:52

问题


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?


回答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"




回答2:


add

position:relative; 

to container div .




回答3:


When giving an element absolute position you take it out of the normal flow of the document. Absolute is the very upper left portion of the screen regardless of the other elements in the page. So by saying left: 50% you're saying half way in from the absolute left of the screen.



来源:https://stackoverflow.com/questions/9404603/absolute-positioning-with-percentages-giving-unexpected-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!