CSS:父 height:auto 和子 height:100% 的定义行为是什么?

CSS: What is the defined behaviour for parent height:auto and children height:100%?

如果父项身高为 auto 且 2 个 height:100% 的子项彼此下方放置,则定义的行为是什么。例如:

<html>
    <style>
        .cont {
            height: auto;
            background-color:silver;
        }
        .box {
            width:50px;
            height:100%;
        }
    </style>
    <body>
        <div class="cont">
            <div class="box" style="background-color:yellow;"> a </div>
            <div class="box" style="background-color:red;"> b </div>
        </div>
    </body>
</html>

https://codepen.io/kisvegabor/pen/XWXVQOX

在 Chrome 和 Firefox 中,子项(或多或少)与屏幕大小相同,但在 CodePen 中,它们的高度适合内容。

您没有为 HTML 提供 DOCTYPE,因此正常的 CSS 规则被以 quirks 模式呈现的页面修改。

您看到的这种效果在 Quirks Mode Living Standard

中有描述

3.5. The percentage height calculation quirk

In quirks mode, for the purpose of calculating the height of an element element, if the computed value of the position property of element is relative or static, the specified value for the height property of element is a <percentage>, and element does not have a computed value of the display property that is table-row, table-row-group, table-header-group, table-footer-group, table-cell or table-caption, the containing block of element must be calculated using the following algorithm, aborting on the first step that returns a value:

  1. Let element be the nearest ancestor containing block of element, if there is one. Otherwise, return the initial containing block.

  2. If element has a computed value of the display property that is table-cell, then return a UA-defined value.

  3. If element has a computed value of the height property that is not auto, then return element.

  4. If element has a computed value of the position property that is absolute, or if element is a not a block container or a table wrapper box, then return element.

  5. Jump to the first step.

按照这个算法,并考虑到怪癖规则 3.6. The html element fills the viewport quirk and 3.7. The body element fills the html element quirk 你会看到 .box 元素的 100% 高度是 body 元素的计算高度的 100% ,即视口高度的 100% 减去 body 元素的默认边距。

Codepen 会自动将 DOCTYPE 添加到您的标记中,因此上述怪癖模式规则不适用。相反,.box 元素的高度由 percentage heights, which states that in your case "the used height is calculated as if 'auto' was specified", and then 10.6.3 Block-level non-replaced elements in normal flow when 'overflow' computes to 'visible' 的正常 CSS 规则确定,即高度是元素内容的高度。