flexbox parent smaller than child elements on browser resize
Flex items, by default, cannot be smaller than the size of their content. Therefore, while the parent can shrink, the flex items cannot shrink past the length of the text. This causes the overflow and, as a result, the column of white space below.
The initial setting on flex items is min-width: auto
. In order for each item to stay within the container, switch to min-width: 0
.
.parent {
height: 400px;
background-color: green;
display: flex;
}
.item {
height: 100px;
background-color: pink;
padding: 10px;
min-width: 0; /* NEW */
}
<div class="parent">
<div class="item">looooooooooooooooooooooooooooong</div>
<div class="item">looooooooooooooooooooooooooooong</div>
</div>
Now the pink boxes are not overflowing the container anymore.
However, the text is now overflowing the pink boxes.
The question doesn't specify behavior for the text, but here's one possible solution:
.parent {
height: 400px;
background-color: green;
display: flex;
}
.item {
height: 100px;
background-color: pink;
padding: 10px;
min-width: 0; /* NEW */
text-overflow: ellipsis; /* NEW */
white-space: nowrap; /* NEW */
overflow: hidden; /* NEW */
}
<div class="parent">
<div class="item">looooooooooooooooooooooooooooong</div>
<div class="item">looooooooooooooooooooooooooooong</div>
</div>
It happens, because your
.parent
is a normal block element (flex is also a block-level container) and that is initialized withwidth:auto;
, which is in your case the width of the viewport. So scrolling to the right will show white space because your div's width is smaller than the whole scrollable area.You do that with setting the
.parent
to an inline element, which will respond to its childrens width.Yes, just use
display: inline-flex;
on the.parent
.
.parent {
height: 400px;
width: 100%;
background-color: green;
display: inline-flex;
}
.item {
flex: 1;
height: 100px;
background-color: pink;
padding: 10px;
}
<div class="parent">
<div class="item">looooooooooooooooooooooooooooong</div>
<div class="item">looooooooooooooooooooooooooooong</div>
</div>
See display
on MDN.