Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force flex children not to overflow the container?

Tags:

css

flexbox

Given a flexbox container, how could I make sure that, if children have lots of content, they don't overflow the container?

.container {
  display: flex;
  flex-direction: column;
  background-color: #ccc;
  height: 210px;
  width: 200px;
}
.child {
  display: flex;
  width: 100px;
}
.first {
  background-color: rgba(255, 0, 0, 0.2);
}
.second {
  background-color: rgba(0, 255, 0, 0.2);
}
.third {
  background-color: rgba(0, 0, 255, 0.2);
}
<div class="container">
  <div class="first child">first first first first first first first</div>
  <div class="second child">second second second second second second second second second second second second second second second second second second second</div>
  <div class="third child">third</div>
</div>

enter image description here

like image 974
Misha Moroshko Avatar asked Mar 16 '18 16:03

Misha Moroshko


People also ask

Why are my flex items overflowing?

This means that if you have a set of flex items that are too wide for their container, they will overflow it. If you want to cause them to wrap once they become too wide you must add the flex-wrap property with a value of wrap , or use the shorthand flex-flow with values of row wrap or column wrap .

How do you make a flex item fill the remaining space?

You can use the flex-grow property to force an item to fill the remaining space on the main axis of a flex container. The item will expand as much as possible and occupy the free area.

Which flex property is used to prevent child element to flow out of parent width?

To override this behavior, use min-width: 0 or overflow: hidden .


1 Answers

The children overflow their parent element because their intrinsic height (the height of their contents) is larger than the parent's height. You can advise the browser to ignore the intrinsic height by setting min-height: 0 on the child elements. If you add overflow: hidden the result should be what you seem to expect:

.container {
  display: flex;
  flex-direction: column;
  background-color: #ccc;
  height: 210px;
  width: 200px;
}
.child {
  width: 100px;
  min-height: 0;
  overflow: hidden;
}
.first {
  background-color: rgba(255, 0, 0, 0.2);
}
.second {
  background-color: rgba(0, 255, 0, 0.2);
}
.third {
  background-color: rgba(0, 0, 255, 0.2);
}
<div class="container">
  <div class="first child">first first first first first first first</div>
  <div class="second child">second second second second second second second second second second second second second second second second second second second</div>
  <div class="third child">third</div>
</div>

The children get height distributed among them proportionally to their content height. Overflowing content is hidden.

like image 60
Wladimir Palant Avatar answered Oct 12 '22 03:10

Wladimir Palant