【发布时间】:2017-03-08 13:47:29
【问题描述】:
据我所知,要以百分比形式工作,容器元素必须具有提到的特定高度。但这不适用于祖先相对定位的绝对定位元素。这是我的意思的一个工作示例:
.container {
width: 400px;
background: cyan;
text-align: right;
position: relative;
color: white;
}
.child {
width: 90%;
height: 100%;
background: blue;
}
.absolute {
position: absolute;
}
.second {
margin-top: 30px;
}
<div class="container">
<div class="child absolute">Absolute</div>
one <br> two <br> three <br> one <br> two <br> three <br>
</div>
<div class="container second">
<div class="child">Static</div>
one <br> two <br> three <br> one <br> two <br> three <br>
</div>
如您所见,绝对放置的 div 应用了 100% 的高度,而不是静态放置的 div。为什么?
【问题讨论】:
-
您的
child元素,因为您没有描述position,默认情况下它是position: static;。要计算您的height: 100%;,父元素应该定义一个height,但它没有。在这种情况下,浏览器不会修改/计算其子项的高度,如果它们不是绝对定位的(因此它们将显示与其内容的大小相匹配)。position: absolute;的情况不同,因为它是在渲染父元素之后计算的。
标签: html css css-position