How do the properties flex-grow and flex-shrink work?
sobes.tech AI
Answer from AI
flex-grow and flex-shrink determine how elements adaptively change their size within a flex container when there is free space or insufficient space, respectively.
flex-grow specifies the factor by which an element should increase when there is free space in the container. The default value is 0 (the element does not stretch). If multiple elements have flex-grow greater than 0, the free space is distributed among them proportionally to their flex-grow values.
.item {
flex-grow: 1; /* The element will use all available free space */
}
flex-shrink specifies the factor by which an element should shrink when there is insufficient space in the container. The default value is 1 (the element shrinks proportionally with other shrinking elements). A value of 0 prevents the element from shrinking.
.item {
flex-shrink: 0; /* The element will not shrink */
}
Together with flex-basis, they form the shorthand property flex: flex: <flex-grow> <flex-shrink> <flex-basis>.
Example of usage:
<div class="container">
<div class="item item-1">Item 1</div>
<div class="item item-2">Item 2</div>
</div>
.container {
display: flex;
width: 400px; /* Example of fixed container width */
}
.item {
flex-basis: 100px; /* Base size of all elements */
}
.item-1 {
flex-grow: 1; /* Item 1 will use free space */
}
.item-2 {
flex-shrink: 0; /* Item 2 will not shrink */
}
If the container is wider than 200px (100px + 100px), item-1 will take all remaining free space. If the container is already 200px, item-2 will keep its base size of 100px, and item-1 will shrink.