百分比的绝对定位会产生意外结果

时间:2021-08-12 20:28:20

Please consider this jsfiddle, containing this html code:

请考虑这个jsfiddle,包含这个HTML代码:

<div id="container">
  <div id="item">TEST</div>
</div>

And some CSS:

还有一些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.

结果让我感到惊讶。看看W3定位道具,我希望#item的左边值为“包含块”的50%:#container。但是,它似乎占整个页面的50%,而不仅仅是包含块。更令人惊讶的是:如果我告诉容器的溢出保持隐藏,“TEST”仍将存在。

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?

所有主流浏览器(包括IE9)似乎都表现出相同的行为,因此我的期望可能不正确。那么问题是:规范的哪一部分解释了这种行为,如果有的话?

3 个解决方案

#1


27  

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.

相对于位置不是静态的下一个父元素应用绝对定位。在您的情况下,这是整页。尝试在容器分区上设置position:relative。看到j​​sFiddle。

See: W3C - 10.1 - Definition of "containing block"

参见:W3C - 10.1 - “包含块”的定义

#2


2  

add

position:relative; 

to container div .

到容器div。

#3


-1  

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.

给出元素绝对位置时,请将其从文档的正常流程中取出。无论页面中的其他元素如何,Absolute都是屏幕的左上角部分。所以说左:50%你说是从屏幕的绝对左侧进入一半。

#1


27  

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.

相对于位置不是静态的下一个父元素应用绝对定位。在您的情况下,这是整页。尝试在容器分区上设置position:relative。看到j​​sFiddle。

See: W3C - 10.1 - Definition of "containing block"

参见:W3C - 10.1 - “包含块”的定义

#2


2  

add

position:relative; 

to container div .

到容器div。

#3


-1  

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.

给出元素绝对位置时,请将其从文档的正常流程中取出。无论页面中的其他元素如何,Absolute都是屏幕的左上角部分。所以说左:50%你说是从屏幕的绝对左侧进入一半。