Sub topic 9
Lay out the navigation and header with Flexbox
This chapter assumes you can write an HTML page with semantic elements, link a stylesheet, and apply CSS rules with selectors. It also assumes you know the box model (margin, padding, border) and that you use box-sizing: border-box. Here you will use Flexbox to turn the navigation list from the page skeleton into a horizontal row, then extend the same ideas to the header.
What Flexbox does
Flexbox is a CSS layout model for arranging items along one line, either a row or a column. You turn it on by setting display: flex on a parent element, called the flex container. Its direct children become flex items.
Flexbox handles one dimension at a time. That makes it a good fit for navigation bars, button groups, card footers and centered content. When you need rows and columns together, use CSS Grid, which the next chapter covers.
Two axes matter:
- The main axis is the direction items flow. By default it runs left to right.
- The cross axis is perpendicular to the main axis. By default it runs top to bottom.
The starting markup
The navigation from the page skeleton is a list of links inside a nav element:
<header>
<nav aria-label="Main">
<ul>
<li><a href="#about">About</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>Without CSS, the ul shows bullets and each li sits on its own line. A list is the right markup anyway. Screen readers announce "list, 3 items", which tells users how many links to expect.
Make the navigation a row
Apply Flexbox to the ul, because its children (the li elements) are the items you want to arrange:
nav ul {
display: flex;
gap: 1.5rem;
justify-content: center;
margin: 0;
padding: 1rem;
list-style: none;
}Each declaration does one job:
display: flexmakes theula flex container. Thelielements line up in a row.gap: 1.5remputs space between items. It adds no space before the first item or after the last one, so you don't need margin tricks.justify-content: centerpositions the group along the main axis, here the horizontal center.margin: 0andpadding: 1remreplace the browser's default list spacing with values you chose.list-style: noneremoves the bullets.
The selector nav ul is a descendant selector. It matches any ul inside a nav, and that is enough for this page. If you later add a list inside the navigation for another purpose, give the navigation list a class such as .site-nav and select that instead.
The properties you will use most
Some properties go on the container and some on the items.
| Property | Goes on | What it controls |
|---|---|---|
| `flex-direction` | Container | Main axis direction: `row` (default), `column`, `row-reverse`, `column-reverse` |
| `justify-content` | Container | Placement of items along the main axis |
| `align-items` | Container | Placement of items along the cross axis |
| `gap` | Container | Space between items |
| `flex-wrap` | Container | Whether items move to a new line when they run out of room |
| `flex` | Item | How an item grows and shrinks (shorthand for `flex-grow`, `flex-shrink`, `flex-basis`) |
| `align-self` | Item | Cross-axis placement for one item |
| `order` | Item | Visual order of one item |
Common values for justify-content are flex-start, center, flex-end, space-between and space-around. For align-items they are stretch (the default), flex-start, center, flex-end and baseline.
Make the links easier to click
The links are small targets. Because the li elements are flex items but the a elements are inline, padding on the a can behave unexpectedly. Make each link a block so its padding counts toward its size:
nav a {
display: block;
padding: 0.5rem 0.75rem;
border-radius: 0.25rem;
text-decoration: none;
}
nav a:hover,
nav a:focus-visible {
background: var(--color-accent);
color: var(--color-bg);
}The hover and focus states share one rule so mouse and keyboard users get the same feedback. The colors come from the custom properties defined in your base styles. Check that white text on the accent color meets the contrast guidance from the accessibility chapter.
Wrapping and small screens
By default, flex items stay on one line. If the container is too narrow, items shrink and may overflow. For a navigation with long labels, allow wrapping:
nav ul {
flex-wrap: wrap;
}With wrapping on, items that don't fit move to a new line, and gap also applies between lines. For three short links this is rarely needed, but it is a safe habit when the number of links may grow.
A header with a name on the left and links on the right
A common header places a site name at one end and the navigation at the other. Add a name to the header:
<header class="site-header">
<a class="site-name" href="#about">Jane Doe</a>
<nav aria-label="Main">
<ul>
<li><a href="#about">About</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>Then make the header itself a flex container:
.site-header {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 1rem;
padding: 0.5rem 1rem;
}
.site-header nav ul {
justify-content: flex-end;
padding: 0;
}space-between pushes the first item to the start and the last item to the end. align-items: center lines the name and the links up vertically, even when their heights differ. flex-wrap: wrap lets the navigation drop below the name on a narrow phone instead of squeezing both.
Notice that you now have nested flex containers. The header lays out the name and the nav. The ul inside the nav lays out the links. Each display: flex affects only its direct children, so every level needs its own declaration.
Common errors
- Flex on the wrong element. Setting
display: flexonnavwhen the items are thelielements inside theuldoes nothing useful, because the only direct child ofnavis theul. Apply it to the element that directly contains the items. - Confusing the axes.
justify-contentfollows the main axis andalign-itemsfollows the cross axis. If you setflex-direction: column, the axes swap, andjustify-contentthen works vertically. - No visible effect from
justify-content. If the container is only as wide as its content, there is no free space to distribute. Block-level containers such asulandheaderfill the available width, so this usually appears withdisplay: inline-flexor a shrink-wrapped parent. - Using margins instead of
gap. Margins on items add space at the edges as well.gapis simpler and has been supported in Flexbox by all current browsers for years. - Reordering with
orderfor appearance only.orderchanges the visual position but not the keyboard or screen reader order. Links can then be focused in an order that doesn't match what users see. Keep the HTML in the order you want people to read it. - Removing list semantics by accident. Setting
list-style: noneon a list can cause some screen readers to stop announcing it as a list. If that matters for your navigation, addrole="list"to theul. Keep the markup otherwise unchanged.
Putting it together
Start from the skeleton with the header markup above. Add the base styles, then the navigation and header rules in this order:
- Base styles: custom properties,
box-sizing, body and links. - Navigation list:
display: flex,gap,justify-content, reset margin, padding and bullets. - Navigation links: block display, padding, hover and focus-visible styles.
- Header: flex container with
space-betweenandalign-items: center. - Wrapping:
flex-wrap: wrapon the header so it adapts to narrow screens.
After each step, save the file and refresh the browser. If a change has no effect, check the selector first, then check that the property is on the container or on the item as the table above says.
Exercise
Your navigation ul has display: flex and three links. You add flex-direction: column. The links stack vertically, but justify-content: center no longer centers them horizontally. Why, and which property would center them horizontally?
Show answer
With flex-direction: column, the main axis runs vertically, so justify-content now centers items vertically (which only shows if the container has extra height). The horizontal direction is now the cross axis, so use align-items: center to center the links horizontally.
Exercise
A header has a site name and a nav list. You want the name at the far left, the links at the far right, both vertically centered, and the nav to move below the name on narrow screens. Write the CSS for the header.
Show answer
.site-header { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 1rem; }