Flexbox Layout
Align and distribute items in one dimension.
What you will learn
- Use flex containers
- Align and space items
- Build a nav bar and cards row
Flexbox lays items out along one axis (a row or a column) and makes alignment, spacing and distributing free space easy. It replaced hacks with floats and is the right tool for nav bars, toolbars, card rows and centering.
The basics
Set display: flex on the container. Its direct children become flex items.
.row {
display: flex;
gap: 1rem; /* space between items */
}<div class="row">
<div>One</div><div>Two</div><div>Three</div>
</div>Two axes
- Main axis: the direction items flow, set by
flex-direction(rowby default, orcolumn). Controlled byjustify-content. - Cross axis: perpendicular to it. Controlled by
align-items.
.bar {
display: flex;
justify-content: space-between; /* start | center | end | space-between | space-around | space-evenly */
align-items: center; /* stretch | start | center | end | baseline */
}.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}How items grow and shrink
Three properties on items control sizing: flex-grow (share of spare space), flex-shrink (willingness to get smaller) and flex-basis (starting size). The shorthand flex: 1 means "grow to fill equally".
.sidebar { flex: 0 0 240px; } /* fixed width, never grows or shrinks */
.content { flex: 1; } /* takes all remaining space */.cards {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.cards > .card {
flex: 1 1 260px; /* at least 260px, share leftover space */
}Items wrap onto new lines when they would drop below their basis, giving a responsive card row without media queries.
.nav {
display: flex;
align-items: center;
gap: 1.5rem;
}
.nav .logo { margin-right: auto; } /* pushes everything after it to the right */Applying flex properties to the wrong element. justify-content and align-items go on the container; flex and align-self go on the children.
Try it yourself
Build a header with a logo on the left and three links on the right, vertically centered. Then make a footer with three columns of equal width.
Show solution
header { display: flex; align-items: center; gap: 1rem; padding: 1rem; }
header .logo { margin-right: auto; }
footer { display: flex; gap: 2rem; }
footer > * { flex: 1; }