CSS
Dynamic Sizing and Filling Space with Flexbox `flex-grow` and `flex-shrink`
Understand how `flex-grow` and `flex-shrink` properties empower flex items to dynamically resize and occupy available space in a flexible container, adapting to content.
.flex-container {
display: flex;
width: 100%; /* Or any defined width */
height: 150px;
border: 1px solid #ccc;
gap: 10px;
padding: 10px;
box-sizing: border-box;
}
.item-a {
flex-grow: 1; /* Item will grow to take available space */
flex-shrink: 1; /* Item can shrink if needed */
flex-basis: 100px; /* Initial size before growing/shrinking */
background-color: lightblue;
padding: 10px;
border: 1px solid blue;
}
.item-b {
flex-grow: 2; /* Item will grow twice as much as item-a */
flex-shrink: 1;
flex-basis: 150px;
background-color: lightgreen;
padding: 10px;
border: 1px solid green;
}
.item-c {
flex-grow: 0; /* Item will not grow */
flex-shrink: 0; /* Item will not shrink */
flex-basis: 80px; /* Stays at 80px */
background-color: lightcoral;
padding: 10px;
border: 1px solid red;
}
/* Example HTML structure */
/*
<div class="flex-container">
<div class="item-a">Item A (grows 1x)</div>
<div class="item-b">Item B (grows 2x)</div>
<div class="item-c">Item C (fixed size)</div>
</div>
*/
How it works: The `flex-grow` and `flex-shrink` properties control how flex items expand or contract to fill or vacate space within their container. `flex-grow` (default `0`) determines an item's ability to grow, relative to other items, when there's extra space. `flex-shrink` (default `1`) determines an item's ability to shrink, relative to other items, when there's insufficient space. `flex-basis` sets an item's initial size before `grow` or `shrink` are applied, providing powerful control over dynamic layouts.