While the parent flex container manages overall alignment, individual child items control how they resize when extra space is available or when space is constrained. This behavior is governed by the flex shorthand property.
The flex Shorthand Syntax
.flex-child {
/* flex: [flex-grow] [flex-shrink] [flex-basis] */
flex: 1 1 auto;
}
Deconstructing the Three Parameters
1. flex-basis
The ideal initial size of the element before available space is distributed.
- Can be
auto, a fixed dimension (300px,20rem), or0/0%. - If set to
auto, the basis is determined by the element's content size or declaredwidth.
2. flex-grow
A unitless factor determining how much of the extra positive free space this item absorbs relative to its siblings:
$$\text{Distributed Space} = \text{Remaining Space} \times \left( \frac{\text{item grow}}{\sum \text{grow}} \right)$$
/* Sibling A gets 1 part, Sibling B gets 2 parts of any extra container space */
.sidebar { flex-grow: 1; flex-basis: 200px; }
.content { flex-grow: 2; flex-basis: 400px; }
3. flex-shrink
A unitless factor determining how aggressively this item shrinks when total item sizes exceed container width (negative free space):
flex-shrink: 1(Default): The item shrinks proportionally.flex-shrink: 0: NEVER shrink. Crucial for preventing icons, profile avatars, and badges from squishing on mobile screens!
Common Production Sizing Archetypes
| Shorthand | Expands To | Behavior | Use Case |
|---|---|---|---|
flex: 0 0 250px | Grow: 0, Shrink: 0, Basis: 250px | Strictly fixed width; never grows or shrinks | Fixed sidebar, avatar icon |
flex: 1 1 0% | Grow: 1, Shrink: 1, Basis: 0% | Completely equal-width columns regardless of content size | Multi-column grid items |
flex: 1 1 auto | Grow: 1, Shrink: 1, Basis: auto | Fluid expansion, but accounts for initial content size | Standard fluid cards |
flex: none | Grow: 0, Shrink: 0, Basis: auto | Fully static sizing based on intrinsic content | Raw action buttons |
/* Classic Holy Grail Sidebar Layout */
.app-layout {
display: flex;
min-height: 100vh;
}
.sidebar {
flex: 0 0 260px; /* Rigid fixed width */
background: #f8fafc;
}
.main-content {
flex: 1 1 0%; /* Consumes all remaining viewport width */
padding: 2rem;
}
Exercises
- Explain why setting
flex: 1(1 1 0%) guarantees equal-width columns whileflex: auto(1 1 auto) creates unequal widths when content lengths differ. - Fix an avatar image that is being squashed in a flex row by applying the appropriate shrink property.
- Calculate the final rendered width of two flex items in an 800px container where Item A has
flex: 1 0 200pxand Item B hasflex: 2 0 300px.