0

I have a button inside a flex box. I wanted to take up as much space as possible, but I also want this flex box to have a min height, because after you click this button it will be replaced by dynamic text. If this dynamic text is really long, I want to flex box to grow in height so that all the text fits.

Here is what I've tried: https://codepen.io/tietyt/pen/xxZRYdd

<div class="container">
    <button disabled="" tabindex="0"> Text </button>
</div>

.container {
    display: flex;
    flex-direction: column;
    margin-bottom: 3em;
    width: 100%;
    text-align: center;
    border-style: outset;
    min-height: 5em;
}

.container button {
    align-self: stretch;
}
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • your question is a perfect duplicate of the one mentionned (and it's not the only one). You need to use one property here which is flex-grow:1 or (flex:1) and there is no more complex than that. I will call another Gold to re-close the question and I will add more duplicate giving the same solution – Temani Afif Jun 22 '20 at 08:02

1 Answers1

2

Based on what you've described, I think you're looking for

flex: auto;

If you add that rule to your button, then it should take up all the available space inside its parent container.

According to the MDN documentation on flex:

auto

The item is sized according to its width and height properties, but grows to absorb any extra free space in the flex container, and shrinks to its minimum size to fit the container. This is equivalent to setting "flex: 1 1 auto".

IlyaMeer
  • 108
  • 5
  • that seems to have worked, thanks. Do you know why my align-self didn't work? – Daniel Kaplan Jun 17 '20 at 19:03
  • @DanielKaplan align and justify, as you'd imagine only control the position of the element inside the flex container. – spaceSentinel Jun 17 '20 at 19:04
  • @VishalAsthana how is "stretch" only a position? Under align-items in this documentation, you can see that it is changing the heights of items: https://css-tricks.com/snippets/css/a-guide-to-flexbox/ – Daniel Kaplan Jun 17 '20 at 19:14
  • 1
    @DanielKaplan In your codepen, `align-self` is stretching your content to fill the available space, but the gotcha is that you've set `flex-direction: column;`. With this setting, the stretching axis has changed from vertical to horizontal. This is why you're seeing your button span the entire length but not the height. An alternative would be to remove `flex-direction` from the `.container` and set `width: 100%; align-self: stretch;` on the button. You would get the same result. – IlyaMeer Jun 17 '20 at 19:23
  • @IlyaMeer Good catch, I hadn't noticed that. – Daniel Kaplan Jun 17 '20 at 19:29