为什么即使没有为包含块给出明确的宽度值,百分比宽度仍然有效?

Why does percentage width work even if no explicit width value given for containing block?

根据 height 的规范,元素的包含框需要有明确的 height 才能使百分比高度作用于元素(即 100% 高度的数值用于所有父包含框)。

但是为什么相同的规则似乎不适用于百分比 widths?当我在一个没有显式 width 的包含框的元素上设置百分比 width 时,它似乎仍然改变了元素的宽度。 (参见示例)

.first {
    background-color: teal;
}
.second {
    background-color: gold;
    width: 30%;  /* the '.second' box becomes narrower! */
    height: 40%; /* <-- doesn't have any effect         */
}
<div class="first">
    ""
    <div class="second">
    ""
    </div>
</div>  

我认为如果没有指定任何其他内容,所有块元素的宽度都是 100%。高度的工作方式不同,因为如果您不在任何地方设置高度,它只会根据内容的总高度来确定高度。

正常流中的非替换块级元素采用其父元素的width

好吧,那是 lie-to-children

为了了解幕后发生的事情,我们应该从 width of a non-replaced block-level element 的计算方式开始。

10.3.3 Block-level, non-replaced elements in normal flow

The following constraints must hold among the used values of the other properties:

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

[...] If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.

由于width属性的初始值为auto,块级元素的width与其包含的元素相同块。

<html> 是一个块级元素,它位于 initial containing block.

初始包含块是一个takes the width of the viewport的矩形框。因此 <html> 元素的宽度将等于视口的宽度。

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

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

W3C 表示更好:

With no positioning, the containing blocks (C.B.) in the following document:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
   <HEAD>
      <TITLE>Illustration of containing blocks</TITLE>
   </HEAD>
   <BODY id="body">
      <DIV id="div1">
      <P id="p1">This is text in the first paragraph...</P>
      <P id="p2">This is text <EM id="em1"> in the 
      <STRONG id="strong1">second</STRONG> paragraph.</EM></P>
      </DIV>
   </BODY>
</HTML>

are established as follows:

For box generated by    C.B. is established by
html                    initial C.B. (UA-dependent)
body                    html
div1                    body
p1                      div1
p2                      div1
em1                     p2
strong1                 p2

然而,对于 height 个未替换的块级元素 (仍在正常流程中!):

情况并非如此

10.6.3 Block-level non-replaced elements in normal flow when 'overflow' computes to 'visible'

[...] If 'height' is 'auto', the height depends on whether the element has any block-level children and whether it has padding or borders.

[...] Only children in the normal flow are taken into account (i.e., floating boxes and absolutely positioned boxes are ignored, and relatively positioned boxes are considered without their offset).

height的初始值为auto,因此如果块级元素没有任何块级子元素、填充或边框,[=23=的计算值] 将是 0.

That's true even for <html> element.