Flex Container Properties Deep Dive
The flex container (parent) controls how its children are distributed, aligned, and wrapped. Master justify-content, align-items, flex-wrap, and align-content — the four properties that control the container's behavior.
Container Properties
- justify-content — Distributes space along the MAIN axis: flex-start, center, flex-end, space-between, space-around, space-evenly
- align-items — Aligns items along the CROSS axis: stretch (default), center, flex-start, flex-end, baseline
- flex-wrap — nowrap (default, items shrink), wrap (items flow to next line), wrap-reverse
- align-content — Controls spacing between WRAPPED rows: only works with flex-wrap: wrap and multiple rows
- gap — Space between items: gap: 16px or row-gap: 16px column-gap: 24px. Replaces margin hacks
- space-between — First item at start, last at end, equal space between. Most common for navbars
- space-evenly — Equal space between AND around items. Most visually balanced distribution
Container Properties Code
/* Common justify-content patterns */
/* Navbar: logo left, links right */
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 24px;
}
/* Center everything */
.center-all {
display: flex;
justify-content: center; /* Horizontal center */
align-items: center; /* Vertical center */
min-height: 100vh;
}
/* Wrapping card grid */
.card-grid {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
/* Align items to baseline (text alignment) */
.mixed-sizes {
display: flex;
align-items: baseline; /* Text baselines align */
gap: 16px;
}Tip
The most-used Flexbox patterns: (1) center everything — justify-content: center + align-items: center, (2) navbar split — justify-content: space-between + align-items: center, (3) card grid — flex-wrap: wrap + gap. Memorize these three and you can build 90% of real-world layouts.
Flexbox is ideal for one-dimensional layouts (row or column)
Common Mistake
Confusing justify-content and align-items. Remember: justify-content = main axis (horizontal in a row), align-items = cross axis (vertical in a row). When flex-direction is column, they swap entirely. This trips up even experienced developers.
Practice Task
Build a navbar: (1) display: flex + justify-content: space-between for logo-left/links-right, (2) align-items: center for vertical centering, (3) gap: 24px on the links. Then build a card grid with flex-wrap: wrap + gap: 20px and resize the browser to see wrapping in action.
Quick Quiz
Key Takeaways
- The flex container (parent) controls how its children are distributed, aligned, and wrapped.
- justify-content — Distributes space along the MAIN axis: flex-start, center, flex-end, space-between, space-around, space-evenly
- align-items — Aligns items along the CROSS axis: stretch (default), center, flex-start, flex-end, baseline
- flex-wrap — nowrap (default, items shrink), wrap (items flow to next line), wrap-reverse