How to stop flex from overflowing the parent

Viewed 233

Concider the following HTML/CSS from this Fiddle

* {
  box-sizing: border-box;
}

html,
body {
  height: 100%;
  margin: 0;
}

main {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
  font-size: 5rem;
}

.fill-rest {
  height: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-items: start;
  background-color: green;
}

.fill-rest div {
  background-color: red;
}
<main>
  <div>Some Text!</div>
  <div>Some Text!</div>
  <div class="fill-rest">
    <div>Overflowing</div>
    <div>Overflowing</div>
    <div>Overflowing</div>
    <div>Overflowing</div>
    <div>Overflowing</div>
    <div>Overflowing</div>
  </div>
</main>

Why - if the divs with "Overflowing" are not present, the height of the element is exactly how I'd want, but as soon as you add too much elements the .fill-rest height becomes 100% of the parent instead of "the remaining space"?

I trying to find a way to make the .fill-rest not overflow main and start wrapping when the remaining space is occupied.

2 Answers

Change your .fill-rest class like this:

.fill-rest {
  display: flex;
  flex-wrap: wrap !important;
  background-color: green;
}

Working example (Try to resize the window to see the wrap of the divs).

After some other search terms, I found out the following from this question:

An initial setting on flex items is min-width: auto. This means that a flex item, by default, cannot be smaller than the size of its content.

Adding min-height: 0; sovled my problem:

* {
  box-sizing: border-box;
}

html,
body {
  height: 100%;
  margin: 0;
}

main {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
  font-size: 5rem;
}

.fill-rest {
  height: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-items: start;
  background-color: green;
  min-height: 0;
}

.fill-rest div {
  background-color: red;
}
<main>
  <div>Some Text!</div>
  <div>Some Text!</div>
  <div class="fill-rest">
    <div>Overflowing</div>
    <div>Overflowing</div>
    <div>Overflowing</div>
    <div>Overflowing</div>
    <div>Overflowing</div>
    <div>Overflowing</div>
  </div>
</main>

Related