Phase 3 — Layout
#10 Flexbox
flex-direction, justify, align, gap
What is Flexbox?
Flexbox is a one-dimensional layout system for arranging items in rows or columns. It excels at distributing space and aligning items.
Container properties
Flex container
.container {
display: flex;
flex-direction: row; /* row | column | row-reverse | column-reverse */
flex-wrap: wrap; /* nowrap | wrap | wrap-reverse */
justify-content: center; /* Main axis alignment */
align-items: center; /* Cross axis alignment */
gap: 16px; /* Space between items */
}Item properties
Flex items
.item {
flex-grow: 1; /* Grow to fill space (0 = don't grow) */
flex-shrink: 0; /* Don't shrink below basis */
flex-basis: 200px; /* Initial size before growing/shrinking */
/* Shorthand */
flex: 1; /* flex: 1 1 0% */
flex: 0 0 auto; /* Don't grow or shrink */
flex: 1 0 200px; /* Grow from 200px, don't shrink */
align-self: center; /* Override container's align-items */
order: -1; /* Reorder visually */
}Common patterns
Navbar
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 24px;
}
.nav-links {
display: flex;
gap: 16px;
}Centering
/* Perfect centering */
.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}Card row
.cards {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
flex: 1 1 300px; /* Grow, shrink, min 300px */
max-width: 400px;
}Your turn
Try the Flexbox commands below:
terminal — browser