Flexbox Layout
Before flexbox, centering something vertically in CSS was famously painful, needing hacky workarounds. Flexbox fixed this entirely. Set display: flex on a PARENT element, and every direct child instantly becomes a 'flex item' arranged in a row by default (or a column, with flex-direction: column). Two properties do most of the work: justify-content controls spacing along the main axis the direction items flow in, usually horizontal with values like center, space-between (items spread to the edges with gaps between), and space-around. align-items controls alignment on the CROSS axis, perpendicular to the main one usually vertical with values like center, flex-start, and flex-end. The gap property adds consistent spacing between items without needing individual margins on each one. A very common beginner mistake is setting these properties on the wrong element they only do anything when applied to the flex container (the parent), not to the individual flex items themselves.
Why this matters
- ·Centers anything, horizontally and vertically, in just 2-3 lines of CSS
- ·Makes navbars and card rows that naturally reflow when the screen size changes
- ·The gap property replaces messy manual margins between items
Common mistakes
- ·Forgetting display: flex on the parent makes justify-content and align-items do nothing at all
- ·Mixing up justify-content and align-items (main axis vs cross axis) is the most common flexbox bug
- ·Setting flex properties on the children instead of the parent container has no effect
Frequently asked questions
It needs to be set on the PARENT element, not the children the children automatically become "flex items" once the parent has it.
Practice questions
Question 1
Change justify-content to center, then space-around, and compare the layouts.
Question 2
Build a row of 3 equal-width boxes using flex: 1 on each.
Quick check
Just for this topic answer honestly, then check yourself.
1 / 10
