CSS
Tutorial: Flexbox step by step - align boxes without suffering
Learn Flexbox by building a navigation bar and a row of perfectly aligned cards.
Before Flexbox, centering a box vertically in CSS was almost a rite of passage (with weird position: absolute tricks and extra math). Not anymore. Breathe.
Step 1: turn a container into flex
<div class="bar">
<div class="logo">My Site</div>
<div class="links">Home | Articles | Tutorials</div>
</div>
.bar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
}
With one line (display: flex) your direct children go from stacking vertically to lining up in a row. justify-content controls the horizontal axis, align-items the vertical one.
Step 2: align cards in a row with even spacing
<div class="cards">
<div class="card">HTML</div>
<div class="card">CSS</div>
<div class="card">JavaScript</div>
</div>
.cards {
display: flex;
gap: 1rem;
}
.card {
flex: 1;
padding: 2rem;
background: #101e27;
border-radius: 0.5rem;
text-align: center;
}
gap adds spacing between the cards without manual margins (goodbye, margin-right on every card except the last one).
Step 3: stack them into a column on small screens
@media (max-width: 600px) {
.cards {
flex-direction: column;
}
}
One more line and your cards go from a row to a column on narrow screens. Flexbox won't solve all your existential problems, but it will solve your alignment ones.
What did you just learn?
- How to enable Flexbox with
display: flex. - How to align elements horizontally and vertically.
- How to switch from a row to a column based on screen size.