绝对定位,百分比给出意想不到的结果 [英] Absolute positioning with percentages giving unexpected results

查看:280
本文介绍了绝对定位,百分比给出意想不到的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑此jsfiddle ,其中包含此html代码:

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

和一些CSS:

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

#item {
border:1px dotted purple;
position:absolute;
left:50%;
}

结果让我吃惊。查看 W3定位道具,我期望#项将其左值设置为包含块的50%: #container 。但是,它似乎在整个页面的50%,而不只是包含块。更令人惊讶的是:如果我告诉容器的溢出隐藏,TEST将仍然存在。



所有主流浏览器同样的行为,所以我的期望可能不正确。 h2_lin>解决方案

绝对定位相对于位置不是静态的下一个父元素应用。在你的情况下,这是整个页面。尝试在容器部门设置 position:relative

请参阅



请参阅 W3C - 10.1 - 包含块的定义


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?

解决方案

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"

这篇关于绝对定位,百分比给出意想不到的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆