How to make flexbox with cross axis overflow have the same height?

旧街凉风 提交于 2020-06-26 09:05:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!