CSS
Dynamic Space Distribution with Flexbox `flex` Shorthand
Master the `flex` shorthand property (`flex-grow`, `flex-shrink`, `flex-basis`) to control how items grow, shrink, and distribute available space within a Flexbox container.
.flex-container {
display: flex;
width: 100%;
border: 1px dashed #ccc;
padding: 10px;
gap: 10px; /* For visual separation */
}
.flex-item {
background-color: #d1e7dd;
padding: 1rem;
border: 1px solid #b3d1c1;
text-align: center;
}
.item-grow-2 {
flex: 2 1 100px; /* flex-grow: 2, flex-shrink: 1, flex-basis: 100px */
}
.item-grow-1 {
flex: 1 1 100px; /* flex-grow: 1, flex-shrink: 1, flex-basis: 100px */
}
.item-no-grow-fixed {
flex: 0 0 150px; /* flex-grow: 0, flex-shrink: 0, flex-basis: 150px (fixed size) */
}
/* Example HTML Structure */
/*
<div class="flex-container">
<div class="flex-item item-grow-2">Item A (Grow x2)</div>
<div class="flex-item item-grow-1">Item B (Grow x1)</div>
<div class="flex-item item-no-grow-fixed">Item C (Fixed)</div>
</div>
*/
How it works: This snippet illustrates the power of the `flex` shorthand property in Flexbox, which combines `flex-grow`, `flex-shrink`, and `flex-basis`. `flex-grow` (first value) dictates how much an item will grow relative to others when there's extra space. `flex-shrink` (second value) controls how an item shrinks when space is constrained. `flex-basis` (third value) defines the item's initial size before growing or shrinking. This allows for precise control over space distribution among flexible items.