HTML 和 BODY 是静态的,哪个是我的 DIV 最接近定位的祖先?



我有这个简单的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>

没有为 htmlbody 定义高度,因此它们使用默认值 auto(这意味着它们的高度是其内容的高度(。它们没有定位,所以它们是静态的。

div.parent1 的高度为 50px。

div.parent1 有一个高度为 50% 的子元素。

div.parent2 位于绝对位置,高度为 25%。

如果我没记错的话,用百分比设置的高度只有在父级定义了高度时才有效(div.child1 就是这种情况(。

因为 div.parent2 是绝对的,所以它的高度不会被计算,所以 bodyhtml 高度是 50px。这很清楚,但我不明白为什么 div.parent2 25% 的高度在起作用......它从哪里来?它的祖先身体和html是静态的...窗?视窗?

JSFiddle

让我们看看 w3 对绝对定位元素的看法:

它们定义一个新的矩形平面,其内容位于该平面中 流动,就像 <BODY> 元素内的 HTML 流入 默认容器。

所以听起来body元素本身代表一个默认容器,无论它是静态的。

取自 w3.org。

或者来自 w3 维基的更好解释。

如果绝对定位的元素没有定位的祖先,则 包含块称为"初始包含" 块",实际上等同于 HTML 元素。如果你是 查看屏幕上的网页,这意味着浏览器窗口;如果 您正在打印页面,这意味着页面边界。

html是一个

块级元素,它位于初始包含块中。

初始包含块是一个矩形框,它采用视口的宽度。因此html元素的宽度将等于视区的宽度。

另一方面,body元素的包含块由 html 生成。因此,它们也将具有相等的宽度。

body本身为其块级子级建立包含块。这就是为什么正常流中的div元素将采用视口的宽度。

见 https://stackoverflow.com/a/28354270/2543240

在没有定位祖先的情况下html"元素"。

对于绝对定位的元素,左侧、右侧和宽度属性的百分比值相对于包含块的宽度。顶部、底部和高度属性的百分比值相对于包含块的高度。

在这种情况下,包含块html元素,

身体没有高度,因为元素不在流动中。

html {
  background: green;
}
body {
  margin: 0;
  padding: 0;
  background: lightblue;
}
.parent2 {
  position: absolute;
  width: 100%;
  height: 25%;
  background: #ff0000;
}
<div class="parent2">I'm absolute positioned. My ancestors, body and html, are static... Where I'm getting the 25% from?</div>

你的HTML是静态的,使用px。百分比是根据浏览器页面高度 - 宽度计算的

最新更新