这是我的代码:
body {
margin: 0;
}
#parent {
width: 100vw;
height: 100vh;
display: flex;
}
#left {
background: blue;
height: 100%;
}
#right {
background: purple;
height: 100%;
}
<div id="parent">
<div id="left">left</div>
<div id="right">right</div>
</div>
根据我的理解,如果没有为 flexbox 子元素指定宽度,它们应该各自占用等量的空间来填充父元素。因此,我认为 #left
和 #right
都将占据 #parent
宽度的 50%,但它们似乎只占用他们需要的空间。
为什么它们不是每个父项的 50%
?
最佳答案
您还需要通过应用 flex-grow: 1
告诉 children 他们可以扩展以填充可用空间。 给两个 child 。另请注意,flex 子项会自动占据父项的全部高度,因此您不需要对子项设置 height: 100%
:
body {
margin: 0;
}
#parent {
width: 100vw;
height: 100vh;
display: flex;
}
#left {
background: blue;
flex-grow: 1;
}
#right {
background: purple;
flex-grow: 1;
}
<div id="parent">
<div id="left">left</div>
<div id="right">right</div>
</div>
关于html - flexbox 的 child 不会占据容器的所有宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49808573/