【发布时间】:2016-02-10 23:32:15
【问题描述】:
我有这个简单的 HTML5 文档:
<!doctype html>
<html>
<head>
<style type="text/css">
body { margin: 0; padding: 0; }
.parent1 { height: 50px; background: #00ff00; }
.parent1 > .child1 { height: 50%; width: 100%; background: #ffcc00; }
.parent2 { position: absolute; width: 100%; height: 25%; background: #ff0000; }
</style>
</head>
<body>
<div class="parent1">
<div class="child1">I'm 25px height (50% of 50px)</div>
</div>
<div class="parent2">I'm absolute positioned. My ancestors, body and html, are static... Where I'm getting the 25% from?</div>
</body>
</html>
html 和 body 没有定义高度,所以它们使用默认值 auto(这意味着它们的高度就是内容的高度)。它们没有定位,所以它们是静态的。
div.parent1 高度为 50 像素。
div.parent1 有一个高度为 50% 的子元素。
div.parent2 绝对定位,高度为 25%。
如果我没记错的话,使用百分比设置的高度只有在它的父级定义了高度时才有效(div.child1就是这种情况)。
因为 div.parent2 是绝对的,所以它的高度是不计算的,所以 body 和 html 的高度都是 50px。这很清楚,但我不明白为什么 div.parent2 25% 的高度有效……它从哪里来的?它的祖先 body 和 html 是静态的……窗口?视口?
【问题讨论】:
-
类似的问题也可以在这里找到:CSS – why doesn’t percentage height work?