Arvind Venkataraman
Arvind Venkataraman

Reputation: 277

Making children of flex item not grow beyond the flex item

I am given a page layout that contains a flex container (with column direction) and a flex item with flex set to 1. I need to add my elements into this flex item. I am looking to fix the height of my container at 100% of the flex item div - but the problem is that my root container's height is dynamic and can keep growing and the height of flex item keeps growing with the height of my root container.

I wouldn't want to set a height on my container - and is there anyway for me to constraint the height of my container.

Here is a much simplified version of what I am looking at. flex-container and flex-items are given to me already. And test-element is my div that I need to put into a page and I need to limit the height of test-element to fit into the 100% of flex-item.

.flex-container {
  display: flex;
  width: 120px;
  height: 120px;
  background-color: pink;
  flex-direction: column;
}

.flex-item {
  background-color: yellow;
  flex: 1;
}

.flex-item.second {
  background-color: blue;
  flex: 0;
}

.test-element {
  background-color: green;
  flex-grow: 1;
  height: 150px;
  // doens't help
  overflow: hidden;
}
<div class="flex-container">
  <div class="flex-item first">
    <div class="test-element"></div>
  </div>
  <div class="flex-item second"></div>
</div>

Upvotes: 5

Views: 13973

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 372099

Instead of setting a fixed height on .test-element, like you have:

.test-element {
  background-color: green;
  flex-grow: 1;
  height: 150px;
  overflow: hidden;
}

Make the parent (.flex-item.first) a flex container. This will automatically apply align-items: stretch to the child (.test-element), causing it to expand the full height of the container. No fixed heights necessary.

.flex-container {
  display: flex;
  flex-direction: column;
  width: 120px;
  height: 120px;
  background-color: pink;
}

.flex-item {
  flex: 1;
  display: flex;   /* new; flex-direction: row, by default */
  background-color: yellow;
}

.test-element {
  flex-grow: 1;
  background-color: green;
}

.flex-item.second {
  flex: 0;
  background-color: blue;
}
<div class="flex-container">
  <div class="flex-item first">
    <div class="test-element"></div>
  </div>
  <div class="flex-item second"></div>
</div>

Upvotes: 4

Related Questions