Flex Sizing
Overview
Aligning items is great, but Flexbox's true math engine lies in how it dynamically resizes children. The flex property (which goes on the CHILD, not the parent) is a shorthand that controls three distinct behaviors: Grow (should it take up extra empty space?), Shrink (should it get smaller if space is tight?), and Basis (what is its ideal starting size?). This allows for incredibly fluid, percentage-free responsive columns.
Syntax
/* The 'flex' property goes on the FLEX ITEM (The child) */
/* Syntax: flex: <flex-grow> <flex-shrink> <flex-basis> */
.sidebar {
/* Grow: 0 (Don't stretch) | Shrink: 0 (Don't crush) | Basis: 250px */
flex: 0 0 250px; /* A perfectly rigid sidebar! */
}
.main-content {
/* Grow: 1 (Take all remaining empty space) | Shrink: 1 | Basis: auto */
flex: 1 1 auto; /* Shorthand: flex: 1; */
}
/*
If two children both have 'flex: 1', they divide the empty space equally 50/50.
If one has 'flex: 2' and the other has 'flex: 1', it's a 66% / 33% split!
*/Common Pitfalls
- Using
width: 250pxinstead offlex-basis: 250pxon a flex item. Whilewidthoften works,flex-basisis specifically designed for the Flex algorithm.flex-basisrespects theflex-direction(it becomesheightif the direction iscolumn), making your layouts infinitely more robust. - Misunderstanding
flex-grow: 1. It does NOT mean 'make this element exactly 100% wide'. It means 'Calculate all the leftover empty space in the container, and give 1 'share' of that space to this element'.
Interview Questions
flex: 1; actually expand to mathematically?It expands to flex-grow: 1; flex-shrink: 1; flex-basis: 0%;. This tells the element to ignore its natural content size and just act as a perfectly fluid fraction of the available space.
Real-World Example
Creating a classic responsive input group (an input field that stretches, with a fixed-size search button).
.search-bar-container { display: flex; }
.search-input {
/* Stretches to fill all remaining space in the navbar! */
flex: 1;
padding: 10px;
}
.search-button {
/* Rigid. Never grows, never shrinks, exactly 100px. */
flex: 0 0 100px;
}Check Your Knowledge
Test your understanding of Flex Sizing with these quick questions.