4

Before this gets stamped with duplicate, there aren't any valid answers that I found on the question similar to mine. (If I'm wrong stamp so I can see that link and I'll be forever grateful!)


If i have a flex container with 2 elements, by default, the container will always default in height to the larger of the two. I want to set the flex containers height to the smaller of the two elements and overflow the larger of the two. How can I set the height of the flex container to match the height of the smaller element?

Some code if anyone needs a basis for the description above:

html

<div class="container">
  <div class="small">
    <div>This is less content</div>
    <div>This is less content</div>
  </div>
  <div class="large">
    <div>random text</div>
    <div>random text</div>
    <div>random text</div>
    <div>random text</div>
    <div>random text</div>
    <div>random text</div>
  </div>
</div>

css

div.container { 
  display: flex;
}

div.small {
  flex: 1;
  background: red;
}

div.large {
  flex: 1;
  background: blue;
  overflow: auto;
}

Here's a codepen to play with: https://codepen.io/andrewsunglaekim/pen/eWJEmM

Andrew Kim
  • 3,145
  • 4
  • 22
  • 42

1 Answers1

4

You could use absolute positioning on the larger element.

div.container { 
  display: flex;
  position: relative;
  justify-content: flex-end;
}

div.small {
  flex: 0 0 50%;
  background: red;
}

div.large {
  position: absolute;
  top: 0; left: 0; bottom: 0;
  right: 50%;
  background: blue;
  overflow: auto;
}
<div class="container">
  
  <div class="large">
    <div>random text</div>
    <div>random text</div>
    <div>random text</div>
    <div>random text</div>
    <div>random text</div>
    <div>random text</div>
  </div>

  <div class="small">
    <div>This is less content</div>
    <div>This is less content</div>
  </div>
</div>
Michael Coker
  • 52,626
  • 5
  • 64
  • 64
  • Thanks, this works, but i had my things switched, and the larger element is on the left. I got the left part to work(larger content) but the smaller content needs to now be absolutely positioned as well? – Andrew Kim Apr 19 '17 at 16:23
  • might be hacky but i just made another flex sibling to ghost in the place of the absolutely positioned one. – Andrew Kim Apr 19 '17 at 16:26
  • @AndrewKim updated my answer to switch the position – Michael Coker Apr 19 '17 at 16:48
  • the actual code base i'm working on must have had other css affecting the positioning, because when i did what you have posted they just sat on top of each other. I'll have to look into it some more but the ghost flex sibling is working for now. Thanks for the help! – Andrew Kim Apr 19 '17 at 17:06