Flexbox Parent Smaller Than Child Elements On Browser Resize
Solution 1:
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 */
}
<divclass="parent"><divclass="item">looooooooooooooooooooooooooooong</div><divclass="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 */
}
<divclass="parent"><divclass="item">looooooooooooooooooooooooooooong</div><divclass="item">looooooooooooooooooooooooooooong</div></div>
Solution 2:
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;
}
<divclass="parent"><divclass="item">looooooooooooooooooooooooooooong</div><divclass="item">looooooooooooooooooooooooooooong</div></div>
See display
on MDN.
Post a Comment for "Flexbox Parent Smaller Than Child Elements On Browser Resize"