jurihandl
jurihandl

Reputation: 665

How do I let a flexbox element grow according to content but not above "flex: 1"

So I have a container with two children. The first children is a list, the second one is a button.

The button should have a fixed height like 40px. If I set the list to "flex: 1" it will grow to consume all the left space of the container minus the 40px the button uses at the bottom.

How do I get the list to grow according to its content (like a normal div), but will only grow to a maximum of consuming all the available space (overflowing if the content is too large)

Here's the html:

.container {
  display: flex;
  height: 300px;
  width: 100px;
  flex-direction: column;
}
.list {
  display: flex;
  flex: 1;
  overflow-y: scroll;
}
.button {
  display: flex;
  height: 40px;
}
<div class="container">
  <div class="list">
    <ul>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
    </ul>
  </div>
  <div class="button">
    View
  </div>
</div>

Here's an example: https://jsfiddle.net/odrbey4c/

The list in the first container should not consume all the space. It should just behave like a normal div. The list in the second container is fine.

Upvotes: 2

Views: 2827

Answers (1)

Paulie_D
Paulie_D

Reputation: 114981

Remove the flex:1 from the list...which is what you want.

However, I believe that you want the button at the bottom of the container. So just add margin-top:auto to the button and it works.

Oh, and change the button to flex: 0 0 40px instead of applying a height so it doesn't shrink at all.

.container {
  display: inline-flex;
  /* for demo only */
  height: 300px;
  width: 100px;
  flex-direction: column;
  border: 1px solid #ff0000;
}
.list {
  display: flex;
  background: #bbb;
  overflow-y: scroll;
}
.button {
  display: flex;
  flex: 0 0 40px;
  margin-top: auto;
  background: #cccccc;
}
<div class="container">
  <div class="list">
    <ul>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
    </ul>
  </div>
  <div class="button">
    View
  </div>
</div>

<div class="container">
  <div class="list">
    <ul>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
    </ul>
  </div>
  <div class="button">
    View
  </div>
</div>

Upvotes: 2

Related Questions