CSS
Dynamic Item Sizing in Flexbox with flex-grow, flex-shrink, flex-basis
Understand and apply `flex-grow`, `flex-shrink`, and `flex-basis` to create highly flexible and dynamic item sizing within a Flexbox container, optimizing space distribution.
.flex-container {
display: flex;
border: 2px solid #333;
padding: 10px;
width: 100%;
min-height: 150px;
gap: 10px;
}
.flex-item {
background-color: #e0e0e0;
padding: 15px;
text-align: center;
border: 1px dashed #666;
}
.flex-item.grow-1 {
flex: 1 1 100px; /* Grow if space, shrink if needed, base width 100px */
background-color: lightcyan;
}
.flex-item.grow-2 {
flex: 2 1 150px; /* Grow twice as much as grow-1, shrink if needed, base width 150px */
background-color: lightgoldenrodyellow;
}
.flex-item.no-shrink {
flex: 0 0 200px; /* Do not grow, do not shrink, fixed width 200px */
background-color: lightpink;
}
How it works: This snippet illustrates the power of the `flex` shorthand property (which combines `flex-grow`, `flex-shrink`, and `flex-basis`) for controlling item sizing within a Flexbox container. `flex-grow` determines how much an item will grow relative to others when there's extra space. `flex-shrink` defines how much an item will shrink when there's not enough space. `flex-basis` sets the initial size of a flex item before any growing or shrinking occurs. This allows for complex and dynamic distribution of space among flex items.