一个 flex/grid 项目设置兄弟姐妹的大小限制

2022-01-30 00:00:00 html css flexbox

I have two sibling elements which each contain dynamic content.

<div class="flex">
    <div class="sibling-1"></div>
    <div class="sibling-2"></div>
</div>

In some cases sibling-1 will have more content then sibling-2 and vice versa. I would like the height of the second element sibling-2 always equal the height of the first sibling-1. If the height of sibling-2 is greater then the height of sibling-1 it will overflow the flex div and thus be scrollable.

Is there any way to accomplish this with Flexbox?

解决方案

Yes, it is possible. Leave the sibling setting the max height alone and set the others' flex-basis: 0 and flex-grow: 1, which according to the spec will expand them to their sibling's height. No absolute positioning. No setting height on any elements.

main {
  display: flex;
}

section {
  display: flex;
  flex-direction: column;
  width: 7em;
  border: thin solid black;
  margin: 1em;
}

:not(.limiter)>div {
  flex-basis: 0px;
  flex-grow: 1;
  overflow-y: auto;
}

<main>
  <section>
    <div>I'm longer and will scroll my overflow. in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text
      in flow text in flow text in flow text in flow text in flow text in flow text in</div>
  </section>

  <section class="limiter">
    <div>Every parent's siblings match my height. in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text</div>
  </section>

  <section>
    <div>I'm shorter but still match the height. in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text in flow text</div>
  </section>
</main>

相关文章