问题
A flex container contains two columns, and the first column could be with any height, so I manually set the height of the container and set overflow: auto
.
What I expected is the right empty div would have the same height as the left sss
box. It's true they have the same height, however it's due to the shrinked height of the left sss
box.(The same height as the container 100px)
.c {
display: flex;
width: 400px;
height: 100px;
overflow: auto;
flex-wrap: nowrap;
}
.empty {
background-color: red;
border: 1px solid;
flex: 1;
}
.sss {
border: 1px solid;
}
<div class="c">
<div class="sss">
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
</div>
<div class="empty">
</div>
</div>
I set margin-top: auto
in the left box, now the height is back to normal (exactly the sum height of all sss
) while the height of the empty box still remain the same.
.c {
display: flex;
width: 400px;
height: 100px;
overflow: auto;
flex-wrap: nowrap;
}
.empty {
background-color: red;
border: 1px solid;
flex: 1;
}
.sss {
margin-bottom: auto;
border: 1px solid;
}
<div class="c">
<div class="sss">
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
</div>
<div class="empty">
</div>
</div>
Then I set flex-wrap: wrap
and it worked, however I don't want them to be wrapped when the width is not enough.
Also, I tried to wrap these two columns in a table and the result is the same as flex-nowrap
.
.c {
display: flex;
width: 400px;
height: 100px;
overflow: auto;
flex-wrap: wrap;
}
.empty {
background-color: red;
border: 1px solid;
flex: 1;
}
.sss {
border: 1px solid;
}
<div class="c">
<div class="sss">
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
</div>
<div class="empty">
</div>
</div>
回答1:
Use CSS grid instead:
.c {
display: grid;
grid-template-columns:auto 1fr;
width: 400px;
height: 100px;
overflow: auto;
}
.empty {
background-color: red;
border: 1px solid;
}
.sss {
border: 1px solid;
}
<div class="c">
<div class="sss">
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
<p>sssss</p>
</div>
<div class="empty">
</div>
</div>
来源:https://stackoverflow.com/questions/62144971/how-to-make-flexbox-with-cross-axis-overflow-have-the-same-height