对于第一种情况,它是关于flexBox的默认对齐方式,即stretch.因此所有元素都将拉伸以适合container1的高度,因此菜单的高度与内容的高度相同.换句话说,最高的元素将定义高度,而另一个将拉伸以适合该高度.@H_301_2@
更改对齐方式,您将不再有此行为:@H_301_2@
@H_301_2@html,body {
height: 100%;
}
.app {
display: flex;
align-items:flex-start; /*anything different from stretch*/
}
.menu {
background-color: red;
width: 100px;
height:100%;
}
.content {
flex: 1;
border: 1px solid blue;
}
通过添加height:100%,您现在可以明确地将高度应用到元素(不再应用拉伸),但这将无法自动设置值(内容的高度),因为父元素没有指定任何高度2@H_301_2@
@H_301_2@html,body {
height: 100%;
}
.app {
display: flex;
}
.menu {
background-color: red;
width: 100px;
height:100%;
}
.content {
flex: 1;
border: 1px solid blue;
}
1 If the cross size property of the flex item computes to auto,and neither of the cross-axis margins are auto,the flex item is stretched. Its used value is the length necessary to make the cross size of the item’s margin Box as close to the same size as the line as possible,while still respecting the constraints imposed by min-height/min-width/max-height/max-width.07001@H_301_2@
在这种情况下,我们只有一行,因此它与整个容器相同.@H_301_2@
@H_301_2@2 Specifies a percentage height. The percentage is calculated with respect to the height of the generated Box’s containing block. If the height of the containing block is not specified explicitly (i.e.,it depends on content height),and this element is not absolutely positioned,the value computes to ‘auto’.07002 @H_301_2@
为应用程序增加一个高度,您将看到正在发生的事情:@H_301_2@
@H_301_2@html,body {
height: 100%;
}
.app {
display: flex;
height:80%;
}
.menu {
background-color: red;
width: 100px;
height:100%;
}
.content {
flex: 1;
border: 1px solid blue;
}
更新@H_301_2@
根据评论,这里是一个特殊情况,其中百分比高度在父元素中未指定高度的情况下工作.@H_301_2@
@H_301_2@html,body {
height: 100%;
}
.app {
display: flex;
height: 80%;
}
.menu {
background-color: red;
width: 100px;
}
.container{
flex: 1;
background:green;
}
.test {
height: 80%;
border: 2px solid blue;
}
正如我在a previous answer中所解释的,.container的高度没有明确设置,但是我们没有任何循环依赖关系,因为.container的高度是由拉伸行为而不是其内容定义的,因此浏览器可以首先设置.container使用Stretch的高度,然后解析.test元素的百分比高度.@H_301_2@
没有拉伸效果,浏览器需要首先根据内容找到高度,并且内容的高度取决于容器,因此我们具有循环依赖性,这将使百分比高度无法自动显示,以便能够定义容器的高度.@H_301_2@