Pattern 1: perfect centering
CSS's historical holy grail —centering something horizontally and vertically— used to be hair-pulling. With flexbox it's trivial: you center on both axes at once with two lines.
.center {
display: flex;
justify-content: center; /* main axis */
align-items: center; /* cross axis */
min-height: 100vh; /* the container needs height to center vertically */
}
The key detail: to center vertically, the container must have height.
Without min-height (or a fixed height) there's no leftover space on the cross
axis and it will look like align-items "does nothing".
Pattern 2: the navigation bar
The most repeated layout on the web: logo on one side, links on the other.
It's solved with justify-content: space-between, which pushes the first and
last child to the edges:
.nav {
display: flex;
justify-content: space-between; /* logo on the left, menu on the right */
align-items: center; /* everything at the same height */
}
.nav ul {
display: flex; /* the links, in turn, in a row */
gap: 24px;
list-style: none;
}
<nav class="nav">
<span class="logo">DevPath</span>
<ul>
<li><a href="#">Courses</a></li>
<li><a href="#">Pricing</a></li>
<li><a href="#">Log in</a></li>
</ul>
</nav>
A very useful variant: if you want the logo on one side and everything else
on the other without relying on space-between, give margin-left: auto to
the first element of the right group. Automatic margins absorb all the
leftover space on the main axis, a very powerful flexbox trick.
Pattern 3: distribute the space (holy grail)
A fixed header, content that takes "whatever is left" and a fixed footer, in a column:
.layout {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.layout main {
flex: 1; /* the content absorbs all the leftover height */
}
The header and footer keep their natural size; flex: 1 on the main makes
the footer stay always at the bottom, even when there's little content. The
same pattern horizontally gives you a fixed sidebar with elastic content:
.app { display: flex; }
.app .sidebar { flex: 0 0 240px; } /* fixed width */
.app .content { flex: 1; } /* the rest */
With these three patterns —centering, space-between and flex: 1— you cover
90% of what you'll need in a real project. Flexbox shines at distributing along
one direction: a row, a column. When you need to command rows and
columns at the same time (a real grid), grid takes over, and that's where we're
headed next.