Sub topic 3
Lay the links out in a row with Flexbox
This chapter turns the plain list of links into a horizontal bar. It assumes you can write basic HTML and CSS selectors and that you know the box model (margin, padding, border). It also assumes the markup from the earlier chapters: a nav element holding a ul of li elements, each containing an a, with the default bullets and spacing already removed.
The model: containers and items
Flexbox is a CSS layout mode. You set display: flex on one element, the flex container. Its direct children become flex items, and the browser lays them out along a line.
The line has two axes:
- The main axis is the direction items flow. With the default
flex-direction: row, it runs left to right in a left-to-right language. - The cross axis is perpendicular to the main axis. With a row, it runs top to bottom.
Only direct children become flex items. Grandchildren are laid out normally inside their parent item. This matters for a navigation bar, because the structure has several levels.
The ul is the container and the li elements are the items. The a elements are not flex items, even though they are what the reader sees and clicks.
Turn the list into a flex container
Here is the markup we are working with.
<nav aria-label="Main">
<ul class="nav-list" id="nav-list">
<li><a href="/" aria-current="page">Home</a></li>
<li><a href="/products">Products</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>This CSS makes the bar horizontal.
.nav-list {
display: flex;
gap: 0.25rem;
margin: 0;
padding: 0;
list-style: none;
background: #1f2937;
}
.nav-list a {
display: block;
padding: 0.75rem 1rem;
color: #ffffff;
text-decoration: none;
}The margin, padding and list-style lines are the reset from the previous chapter. The new line is display: flex. Without it, the li elements stack because they have the default display: list-item. With it, they become flex items and sit side by side.
The ul is a block-level flex container, so it still spans the full width of its parent, and the background fills the whole bar. If you used display: inline-flex, the container would shrink to fit its content and the colored bar would end after the last link.
Why the flex rule goes on the ul
A common first attempt is to put display: flex on nav. That makes the ul the only flex item, and the li elements still stack inside it. The rule must go on the element that directly contains the items you want in a row.
You can still put display: flex on the nav for a different purpose, such as placing a logo next to the list. Then the nav is a container for the logo and the ul, and the ul is a second container for the links. Nested flex containers are normal.
Space between items with gap
The gap property sets the space between flex items. It does not add space before the first item or after the last one. That is the main reason to prefer it over margins on each li.
With margins, you usually need a special rule to remove the extra space at one end. With gap, the spacing is uniform and lives on the container, so you change it in one place.
gap is shorthand for row-gap and column-gap. In a single-row bar only column-gap has a visible effect, because it is the space along the main axis. When the list wraps onto several lines (see below), row-gap controls the space between the lines.
.nav-list {
column-gap: 0.25rem;
row-gap: 0.5rem;
}If you want the links to touch, with no space between them, set gap: 0. Many bars do this and rely on link padding and hover backgrounds to separate the items.
Distribute items along the main axis
By default, flex items pack at the start of the main axis, so the links sit at the left and the remaining space is empty on the right. The justify-content property controls how free space on the main axis is distributed.
| Value | Effect on a row of links |
|---|---|
| `flex-start` (default) | Items packed at the left |
| `center` | Items packed in the middle |
| `flex-end` | Items packed at the right |
| `space-between` | First item at the left edge, last at the right edge, equal space between |
| `space-around` | Equal space around each item, so edge gaps are half the inner gaps |
| `space-evenly` | Equal space between items and at both edges |
For a centered bar:
.nav-list {
justify-content: center;
}justify-content only has an effect when there is free space. If the items already fill the line, there is nothing to distribute. It also works with gap: the gap is a minimum, and any leftover space is added on top of it.
Align items on the cross axis
align-items controls placement along the cross axis, which for a row is vertical. Its default is stretch, so every li grows to the height of the tallest item in the row.
Stretching is usually what you want in a navigation bar. When one item is taller than the others, for example because its label wraps onto two lines, all the items match its height and the hover backgrounds line up.
If you want items to keep their natural height instead, set align-items:
.nav-list {
align-items: center;
}With center, shorter items sit in the vertical middle of the bar. With flex-start they sit at the top. Be aware that with anything other than stretch, the li is only as tall as its link. A hover background on the li then no longer fills the bar, which is why the earlier CSS puts the padding and hover color on the a.
Push one item to the far side with auto margins
A common layout has most links on the left and one, such as "Log in", on the right. You can do this without changing justify-content. In a flex container, an auto margin absorbs all the free space on that side of the item.
<ul class="nav-list">
<li><a href="/">Home</a></li>
<li><a href="/products">Products</a></li>
<li><a href="/about">About</a></li>
<li class="nav-end"><a href="/login">Log in</a></li>
</ul>.nav-end {
margin-left: auto;
}The browser gives all the leftover main-axis space to the left margin of .nav-end. That pushes the item, and any items after it, to the right edge. Auto margins are applied before justify-content, so when an auto margin is present, justify-content has no free space left to distribute.
What happens when there is not enough room
A flex container has flex-wrap: nowrap by default. All items stay on one line, and each item's flex-shrink value of 1 lets it get narrower than its natural width. Items shrink only down to their minimum content width, which is usually the width of the longest word.
This has two consequences:
- Multi-word link labels wrap onto several lines before the bar overflows. A label like "Contact us" may break into two lines on a narrow screen.
- When even the minimum widths do not fit, the items overflow the container and can create a horizontal scrollbar on the page.
You have three options. The first is to stop labels from wrapping, which makes overflow happen sooner.
.nav-list a {
white-space: nowrap;
}The second is to let the whole item move to a new line.
.nav-list {
flex-wrap: wrap;
}With flex-wrap: wrap, an item that does not fit starts a new row, and row-gap sets the space between rows. The third option is to change the layout at small widths, so that the links stack in a column behind a toggle button. A later chapter covers that with a media query. Wrapping is a reasonable fallback, but a wrapped navigation bar with ragged rows rarely looks deliberate.
Try the whole thing
Save this as a single file and open it in a browser. It contains the markup and the layout rules from this chapter.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Flex navigation bar</title>
<style>
body {
margin: 0;
font-family: system-ui, sans-serif;
}
.nav-list {
display: flex;
gap: 0.25rem;
margin: 0;
padding: 0;
list-style: none;
background: #1f2937;
}
.nav-list a {
display: block;
padding: 0.75rem 1rem;
color: #ffffff;
text-decoration: none;
white-space: nowrap;
}
.nav-end {
margin-left: auto;
}
</style>
</head>
<body>
<nav aria-label="Main">
<ul class="nav-list" id="nav-list">
<li><a href="/" aria-current="page">Home</a></li>
<li><a href="/products">Products</a></li>
<li><a href="/about">About</a></li>
<li class="nav-end"><a href="/contact">Contact</a></li>
</ul>
</nav>
</body>
</html>Experiment with it. Remove the display: flex line and watch the links stack. Change .nav-end to margin-right: auto on the "Home" item and see where the free space goes. Set flex-wrap: wrap and narrow the window.
Common errors
- Flex on the wrong element. Putting
display: flexonnavor on eachlileaves thelielements stacked. Apply it to theul. - Expecting the links to be flex items. The
aelements are children ofli, so properties likeflex-growon theado nothing. Put item-level properties on theli. - Using
display: flexonliby mistake. This turns theliinto a container for its link, which is sometimes useful for centering text, but it does not put the list items in a row. - Margins that leave an extra gap at one end. Use
gapon the container instead of margin on each item. - Forgetting that
justify-contentneeds free space. If the content already fills the line, changingjustify-contentshows no change. - Using
align-items: centerand losing the full-height hover area. Keep the padding on thea, or return tostretch. - Ignoring overflow. Test at a narrow width. Unwrapped labels and a long list will push the page wider than the viewport.
Exercise
You have a ul.nav-list with display: flex and five links. You want the first four links on the left and the fifth, "Log in", on the right, with 0.5rem between the left-hand links. You do not want to change justify-content. Which CSS do you write, and on which element does the second rule go?
Show answer
Set gap: 0.5rem on .nav-list for the spacing, and add margin-left: auto to the fifth li (for example li.nav-end). The auto margin takes all the free space on its left, which pushes "Log in" to the right edge. The rule goes on the li, not on the a, because the li is the flex item.
Exercise
A teammate sets display: flex on the nav element, and the links are still stacked. Why, and what is the fix?
Show answer
A flex container only affects its direct children. The direct child of nav is the ul, so the ul becomes the single flex item, and the li elements inside it keep their normal vertical layout. The fix is to move display: flex to the ul (.nav-list).