相对div的高度是100%,直到我实际设置高度:100%



设置

.container {
position: relative;
display: flex;
flex-direction: row;
justify-content: flex-start;
flex: 1 1;
padding: 28px;
width: 100%;
background-color: #eee;
}
.bar {
position: relative;
width: 5px;
background-color: blue;
}
<div class="container">
<div class="bar"></div>
<div>
lskdjf
</div>
</div>

请注意,蓝色条达到容器的全部高度,减去填充。

但是,如果将height: 100%添加到.bar类中,则高度将消失。

.bar {
position: relative;
width: 5px;
background-color: blue;
height: 100%;
}

问题

我想,实际上将高度设置为100%会混淆浏览器,因为父对象实际上没有设置高度,但什么属性pre-setting-height-100%允许高度为100%?而且,考虑到这实际上是我的目标,不指定100%是"正确的"吗?或者有更好的方法来确保.bar元素达到最大高度吗?

这是由于应用于flexbox容器的拉伸默认对齐方式使所有元素拉伸以适应其父元素的高度。

.container {
position: relative;
display: flex;
flex-direction: row;
justify-content: flex-start;
flex: 1 1;
padding: 28px;
width: 100%;
background-color: #eee;
}
.bar {
position: relative;
width: 5px;
background-color: blue;
}
<div class="container">
<div class="bar"></div>
<div>
lskdjf
</div>
</div>

如果弹性项的交叉大小属性计算为自动,并且两个交叉轴边距都不是自动的,则弹性项被拉伸。它使用的值是使项目的边距框的交叉大小尽可能接近行的大小所需的长度,同时仍然遵守最小高度/最小宽度/最大高度/最大宽度所施加的限制ref

如果您更改对齐方式,将不再发生这种情况

.container {
position: relative;
display: flex;
flex-direction: row;
justify-content: flex-start;
flex: 1 1;
padding: 28px;
width: 100%;
background-color: #eee;
align-items:flex-start;
}
.bar {
position: relative;
width: 5px;
background-color: blue;
}
<div class="container">
<div class="bar"></div>
<div>
lskdjf
</div>
</div>

如果设置任何高度值,考虑到上述规范,大小将不再是自动的,因此拉伸将不再适用,并且您将陷入高度百分比的问题,这将使高度降至自动,因为父高度没有明确设置。

指定百分比高度。百分比是根据生成的长方体的包含块的高度计算的。如果未显式指定包含块的高度(即,它取决于内容高度(,并且此元素不是绝对定位的,则该值计算为"auto">ref