html - 为什么 CSS 百分比 (%) 高度应用于 flex 元素的孙子?

标签 html css flexbox

我正在尝试检查 CSS 100% height 属性是如何工作的。但有一点我无法理解。

为什么 100% 高度在 .flex-grand-child 上完美运行( Chrome )?是否 .flex-child有高度属性吗?那为什么它甚至可以工作???

这里是 JSFiddle

html, body {
  height: 100%;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.flex-parent {
  flex: 1 0 auto;
  display: flex;
}

.flex-child {
    width: 300px;
}

.flex-grand-child {
   height: 100%;
   background-color: green;
}
<div class="container">
    <div class="flex-parent">
        <div class="flex-child">
          <div class='flex-grand-child'></div>
        </div>
    </div>
</div>

最佳答案

这是一种特殊情况,由于 flexbox 的拉伸(stretch)效果,浏览器可以处理高度的百分比值。 flex-child具有等于​​拉伸(stretch)的默认对齐方式,相当于具有 height:100%然后 flex-parent也用 flex-grow:1 填充其父高度.最后,浏览器能够正确解析height:100%。的 flex-grand-child

If the flex item has align-self: stretch, redo layout for its contents, treating this used size as its definite cross size so that percentage-sized children can be resolved.ref


如果禁用拉伸(stretch)对齐,它将中断:

html,
body {
  height: 100%;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.flex-parent {
  flex: 1 0 auto;
  display: flex;
}

.flex-child {
  width: 300px;
  min-height: 200px;
  align-self: flex-start; /*this will break it*/
  border: 1px solid;
}

.flex-grand-child {
  height: 100%;
  background-color: green;
}
<div class="container">
  <div class="flex-parent">
    <div class="flex-child">
      <div class='flex-grand-child'></div>
    </div>
  </div>
</div>

简单来说:当有拉伸(stretch)效果时,浏览器会先根据自己的父级定义父级高度(这里内容不做任何作用),然后浏览器将内容设为height:100%之前计算的高度。如果不拉伸(stretch),浏览器需要考虑内容来定义父级的高度,这里我们将陷入经典的百分比高度问题。

获得更多无需在父元素上定义显式高度即可解决百分比的相关问题:Why is my Grid element's height not being calculated correctly?
以下是规范的相关部分:https://www.w3.org/TR/css-sizing-3/#percentage-sizing
它有点复杂,但与 the CSS2 specification 不同。如果未指定父高度,则百分比将始终失败:

If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.

关于html - 为什么 CSS 百分比 (%) 高度应用于 flex 元素的孙子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61941815/

相关文章:

html - html5中的YouTube视频未显示我选择的视频

javascript - 如何检测哪些复选框被选中?

html - 显示 PDF 文件的图标

html - 选择具有可点击图像组件的元素

javascript - 隔离较少的样式以响应组件

javascript - AngularJS 图表文件问题

html - 无法添加粗体或斜体文本

html - A4 论文样 CSS : taking citations from the main column and placing them into the other

html - Flexboxs child 溢出 parent

html - 子高度未知的 CSS Flexbox 布局 100%