gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:12:36 26 4
gpt4 key购买 nike

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

但是,为什么相同的规则似乎不适用于百分比 width?当我在包含没有显式 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>

最佳答案

正常流中的非替换 block 级元素采用width他们的 parent 。

嗯,那是一个 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 block 级元素的元素与其包含 block 相同。

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

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

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

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

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 而言,情况并非如此。未替换的 block 级元素(仍在正常流程中!):

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 ,因此如果 block 级元素没有任何 block 级子元素、填充或边框,则 height 的计算值将是 0 .

That's true even for <html> element .

关于html - 为什么即使没有为包含 block 给出明确的宽度值,百分比宽度仍然有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28353625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com