我想了解为什么带有青色边框的绿色 div 在这些情况下会有这样的行为。
无额外包装:
.wrapper {
display: flex;
border: solid 2px black;
}
.red {
width: 25px;
height: 25px;
background-color: red;
}
.green {
height: 100%;
background-color: green;
border: solid 2px cyan;
}
.blue {
width: 50px;
height: 50px;
background-color: blue;
}
<div class="wrapper">
<div class="red"></div>
<div class="green"></div>
<div class="blue"></div>
</div>
结果:绿色 div 的高度为零,而不是蓝色的高度。
带有额外的包装。均带有显示弹性:
.wrapper {
display: flex;
border: solid 2px black;
}
.red {
width: 25px;
height: 25px;
background-color: red;
}
.green {
height: 100%;
background-color: green;
border: solid 2px cyan;
}
.blue {
width: 50px;
height: 50px;
background-color: blue;
}
<div class="wrapper">
<div class="wrapper">
<div class="red"></div>
<div class="green"></div>
<div class="blue"></div>
</div>
</div>
结果:正如预期的那样,绿色 div 具有蓝色的高度。
带有额外的包装。只有带有显示弹性的祖父级:
.wrapper {
display: flex;
border: solid 2px black;
}
.red {
width: 25px;
height: 25px;
background-color: red;
}
.green {
height: 100%;
background-color: green;
border: solid 2px cyan;
}
.blue {
width: 50px;
height: 50px;
background-color: blue;
}
<div class="wrapper">
<div>
<div class="red"></div>
<div class="green"></div>
<div class="blue"></div>
</div>
</div>
结果:绿色 div 具有蓝色 + 红色 + (青色边框 * 2)的高度,与预期一致。
为什么我必须添加一个具有显示弹性的包装器才能使高度百分比按照我期望的方式工作?
编辑
经过一番修修补补,我发现了一些东西。在第一个例子中,删除height: 100%
(或将其设置为自动)会使其增大。为什么当绿色 div 的高度为自动时,它会占用父级的全部高度(减去其自身的边框),而当设置为 100% 时则不会?
.wrapper {
display: flex;
border: solid 2px black;
}
.red {
width: 25px;
height: 25px;
background-color: red;
}
.green {
height: auto;
background-color: green;
border: solid 2px cyan;
}
.blue {
width: 50px;
height: 50px;
background-color: blue;
}
<div class="wrapper">
<div class="red"></div>
<div class="green"></div>
<div class="blue"></div>
</div>
第一个例子(没有额外的包装)
带有 的绿色 div
height: '100%'
被设置为与其包含块(即带有 的父 div)的高度相同display: 'flex'
。但是,父 div 的高度是不确定的,因此其height: '100%'
行为将类似于height: 'auto'
。并且绿色 div 中没有内容,因此其高度为零。W3C CSS 标准:高度 - 百分比
W3C CSS 标准:包含块
W3C CSS 标准:确定大小和不确定大小
第二个示例(带有额外的包装器。均带有显示弹性)
绿色 div 的包含块仍然是其父 div
display: 'flex'
,即额外的包装器。这里有一个区别,包装器有一个父级display: 'flex'
,即 ,这意味着包装器现在是一个弹性项目。根据弹性布局算法,包装器的大小将被视为确定的。现在 100% 将生效,使绿色 div 具有与包装器相同的高度。抛开一些细节,布局流程如下:
25px
。height: '100%'
,但是它的包含块的高度现在不确定,因此将其视为height: 'auto'
,这给出内容高度0 + 边框 * 2。绿色的高度为4px
。50px
。50px
。50px
。50px
。然后其子女的身高设置为50px
且确定。25px
和50px
。50px
。总高度将加上边框 * 254px
。W3C CSS 标准:弹性布局算法 - 明确大小
W3C CSS 标准:弹性布局算法 - 跨尺寸判定
第三个示例(带有额外的包装器。只有祖父母具有显示弹性)
该过程与第二个示例类似。不同之处以粗体和斜体显示。
25px
。height: '100%'
,但是它的包含块的高度现在不确定,因此将其视为height: 'auto'
,这给出内容高度0 + 边框 * 2。绿色的高度为4px
。50px
。79px
。79px
。79px
。然后其子女的身高设置为79px
且确定。25px
和50px
。79px
。总高度将加上边框 * 283px
。顺便提一句
box-sizing: 'border-box'
以避免添加边框线宽度的麻烦。height
从第一个示例的绿色中移除。align-items: stretch
默认情况下,弹性布局会拉伸绿色的高度以将最高的项目与其交叉线对齐。否则,显式高度将覆盖拉伸。