Introduction to Flexbox
Prerequisites: The display property
Flexbox lays out items in a row or column, distributing space and aligning them. It's the tool for navigation bars, toolbars, button groups, and centering.
.navbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.75rem 1rem;
}
display: flex makes the element a flex container; its direct
children become flex items.
Two axes
- The main axis runs in the
flex-direction— horizontal forrow(the default), vertical forcolumn. - The cross axis is perpendicular to it.
| Property (on the container) | Controls |
|---|---|
flex-direction |
row, row-reverse, column, column-reverse |
justify-content |
Main-axis distribution: flex-start, center, flex-end, space-between, space-around, space-evenly |
align-items |
Cross-axis alignment: stretch (default), flex-start, center, flex-end, baseline |
flex-wrap |
nowrap (default) or wrap onto more lines |
gap |
Space between items |
See the layout
<style>
.bar { display: flex; justify-content: space-between; align-items: center; width: 400px; height: 60px; }
.bar > * { width: 80px; height: 20px; }
</style>
<div class="bar"><div id="a"></div><div id="b"></div><div id="c"></div></div>
<script>
const bar = document.querySelector(".bar").getBoundingClientRect();
for (const id of ["a", "b", "c"]) {
const r = document.getElementById(id).getBoundingClientRect();
console.log(id, "left:", r.left - bar.left, "top:", r.top - bar.top);
}
</script>
a left: 0 top: 20
b left: 160 top: 20
c left: 320 top: 20
space-between put the first item at the start, the last at the end,
and split the remaining 160 pixels equally (80 each). align-items: center placed each 20-pixel item 20 pixels down in the 60-pixel bar.
Centering anything
.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100dvh;
}
Growing and pushing
.search-row { display: flex; gap: 0.5rem; }
.search-row input { flex: 1; }
.navbar .login { margin-left: auto; }
flex: 1on an item lets it grow to take the leftover space — here the input fills the row next to a fixed-size button.- An
automargin absorbs free space, pushing the item (and anything after it) to the far end.
Wrapping
.tags { display: flex; flex-wrap: wrap; gap: 0.5rem; }
Without wrap, items shrink to fit on one line and can overflow.
Level 2 covers flex-grow, flex-shrink, flex-basis, and alignment
in depth, and CSS Grid for two-dimensional layouts.
Practice
Lay out a footer with three links spread evenly across the width, vertically centered, that wrap onto new lines on small screens.
Show solution
.footer-links {
display: flex;
flex-wrap: wrap;
justify-content: space-evenly;
align-items: center;
gap: 1rem;
}