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

标签 html css

我有这个简单的 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 高度为 50 像素。

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

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

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

因为div.parent2是绝对的,所以它的高度没有被计算,所以bodyhtml高度都是50px。这很清楚,但我不明白为什么 div.parent2 25% 的高度有效……它从哪里来?它的祖先body和html都是静态的……窗口?视口(viewport)?

JSFiddle

最佳答案

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

They define a new rectangular plane into which their contents are flowed, just as the HTML inside the <BODY> element flows into the default container.

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

取自 w3.org .

或者来自 w3 wiki 的更好解释.

If an absolutely positioned element has no positioned ancestor, then the containing block is something called the “initial containing block,” which in practice equates to the html element. If you are looking at the web page on screen, this means the browser window; if you are printing the page, it means the page boundary.

关于HTML 和 BODY 是静态的,哪个是我的 DIV 最接近的定位祖先?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35318546/

相关文章:

PHP、MySQL - 将复选框与下拉列表相关联

javascript - 图像 slider 的响应式设计不符合预期

php - 更新数据库时缺少参数错误

css - 如何在ie8中对同一个div同时使用阴影和不透明度

html - Div 100% 高度显示为 0px?

javascript - 动画的心图标

javascript - html中的鼠标悬停效果

javascript - 动态添加图像的媒体查询

css - 使用 SASS & 定位父类的第二类

javascript - 我需要在网页中制作一个按钮来放大和缩小(辅助功能控件)(禁用友好)