Can we use flex-wrap and flex-shrink on the same flex container?
Answer
We can use flex-wrap and flex-shrink on the same container, flex-wrap does not negate the use of flex-shrink. Take for example an instance where our content would otherwise overflow our container:
HTML:
section {
display: flex;
width: 300px;
border: 1px solid black;
flex-wrap: wrap; /*content wraps when not enough space is available to have all content on a single line*/
}
div {
width: 100px;
height: 100px;
border: 1px solid red;
flex-shrink: 0; /*override default to `flex-shrink: 0;` for all divs, divs will not shrink if not enough space is available*/
}
.four {
width: 400px; /*.four div overflows our flex container*/
}
vs
CSS without overflowing content:
section {
display: flex;
width: 300px;
border: 1px solid black;
flex-wrap: wrap; /*content wraps when not enough space is available to have all content on a single line*/
}
div {
width: 100px;
height: 100px;
border: 1px solid red;
flex-shrink: 1; /*`flex-shrink` set to 1 (default), divs will shrink if not enough space is available*/
}
.four {
width: 400px; /*.four div no longer overflows our flex container*/
}
in this exercise i add flex-shrink: 2; to box elements, but no changes happened, if i shrink browser, the box with warp property just take more line without shrinking box elements and boxes with parent nowarp still shrinking like before. so what notice i miss?
@aubsrey, Thank you for trying to explain but now Iâm kind of confused . I still do not understand how .four div -which is specified with a width of 400px- does not overflow itâs parent container that has a width of 300px⌠I thought specifying the width of an element using pixels is like âhard-codingâ it.
@byte4235076416 itâs simple. All flex items by default have a flex-shrink value of 1. So if the div overflows its container it has to be shrinked to fit in. If you want it to overflow youâd have to set the flex-shrink to zero.
You can revise the early lessons on flex box where it is mentioned that when a containerâs dimension is specified the flex items shrink to fit in.
Is there any way of getting a flex item to shrink to a minimum width before it wraps on to the next line? I tried setting a min-width but it didnât work.
Itâs not really limiting the amount that an element shrinks so much as setting the minimum width with flex-basis, allowing growth, and setting wrapping in the container.
So in your case youâd just need to set your desired min-width as the flex-basis.