CSS
Master Responsive Item Sizing and Distribution with Flexbox `flex` Shorthand
Master the powerful `flex` shorthand property to control how individual flex items grow, shrink, and establish their initial size within a flex container.
.flex-container {
display: flex;
gap: 10px; /* Spacing between items */
border: 1px solid #ccc;
padding: 10px;
}
.flex-item {
background-color: #e0f2f7;
padding: 15px;
text-align: center;
}
/* Item 1: Grows and shrinks, initial size 200px */
.flex-item-1 {
flex: 1 1 200px;
}
/* Item 2: Grows at twice the rate of others, shrinks equally, initial size 100px */
.flex-item-2 {
flex: 2 1 100px;
}
/* Item 3: Does not grow or shrink, fixed width of 150px */
.flex-item-3 {
flex: 0 0 150px;
}
/* Example of a full-width item in a wrapped layout */
.full-width-item {
flex: 1 1 100%; /* Takes full width available, grows/shrinks */
}
How it works: The `flex` shorthand property (`flex-grow`, `flex-shrink`, `flex-basis`) is crucial for controlling the responsiveness and distribution of space among flex items. `flex-grow` (first value) determines how much an item will grow relative to others when space is available. `flex-shrink` (second value) dictates how much it will shrink when space is constrained. `flex-basis` (third value) sets the item's initial size before any growing or shrinking occurs. This snippet demonstrates various combinations to achieve different sizing behaviors.