Master CSS Flexbox to build one-dimensional layouts β rows and columns β with powerful alignment, spacing, and ordering controls.
Background
Flexbox (Flexible Box Layout) is a CSS layout model designed for distributing space and aligning items in a single axis. It solves common layout challenges like centering elements, equal-height columns, and responsive navigation bars that were painful with older CSS techniques.
π‘ Why Flexbox? Before flexbox, centering elements vertically required hacks. display: flex on a parent turns all direct children into flex items. justify-content controls alignment along the main axis (horizontal by default), while align-items controls the cross axis (vertical).
πΈ Verified Output:
Step 2: Flex Items β Grow, Shrink, Basis
Write this file:
π‘ The flex shorthand is flex: grow shrink basis. Item A takes 2Γ more of available space than B. Item C is rigid β it never grows or shrinks. flex: 1 is shorthand for flex: 1 1 0% β equal distribution of all available space.
πΈ Verified Output:
Step 3: Flex Wrap & Alignment
Write this file:
π‘ flex-wrap: wrap allows flex items to break onto multiple lines when they don't fit. gap adds spacing between items (replaces margin hacks). align-content controls how multiple rows align in the container β only works when flex-wrap is active.
πΈ Verified Output:
Step 4: Order & align-self
Write this file:
π‘ order changes visual display order without modifying HTML β great for responsive layouts where mobile and desktop need different orderings. align-self lets individual items override the container's align-items value.
πΈ Verified Output:
Step 5: Navigation Bar with Flexbox
Write this file:
π‘ This is the most common flexbox pattern. Logo on left, links centered, CTA on right β justify-content: space-between handles the spacing automatically. Nested flexbox (nav-links is also a flex container) is perfectly valid and widely used.
πΈ Verified Output:
Step 6: Card Grid with Flexbox
Write this file:
π‘ Equal-height cards with bottom-aligned buttons β the holy grail of card design. The trick: make the card a flex-direction: column, give the text flex: 1 so it stretches, and the button naturally stays at the bottom. Pure flexbox, no JavaScript.
πΈ Verified Output:
Step 7: Holy Grail Layout
Write this file:
π‘ Two layers of flexbox: The body is a flex column (stacking header/content/footer). The .content-area is a flex row (sidebars + main). flex: 1 on main makes it take all remaining space. flex-shrink: 0 on sidebars prevents them from getting squeezed.
πΈ Verified Output:
Step 8: Capstone β Responsive Product Card
Write this file:
π‘ Capstone recap: This card uses flexbox at three levels β body centering, card column layout, and footer row layout. The pattern (flex container β column β footer space-between) is used in virtually every modern card component. Master this and you'll recognize it everywhere.