When a website has multiple pages, moving between them is easier if you provide navigation links, or navlinks. These often appear in a header at the top of the page in this general form:
Let's explore an idiomatic way of forming these navlinks. You start with a sequence of anchor tags:
To bind these together, you place them in an unordered list—not because you want them to look like a bulleted list, but because an unordered list has the right semantic meaning. To allow yourself to target these elements with surgical precision, you also add some classes:
Notice how the list has plural navlinks
while the list items have the singular navlink
.
To accommodate visitors using screen readers, you place your list inside the semantic nav
element:
The browser's default styling of an unordered list is far from your target. You don't want those bullets or any extra spacing, which you turn off using the list-style-type
, margin
, and padding
properties:
Try setting the list's background color to black. How does that look? The text is probably unreadable. Many browsers will show dark text on a dark background.
Try lightening the text by setting the list item's foreground color to white. Does that fix the problem? No. That's because the anchor tags do not inherit the foreground color from the list item. Instead, the browser assigns a default color to links.
You override the browser's color with your own by directly targeting the anchor tags in your CSS. To avoid coloring all anchor tags, you use a direct descendent selector to only style anchors that are children of .navlink
:
Instead of a vertical stack of links, you want a right-aligned horizontal stack, which you can achieve using Flexbox and its justify-content
property:
Those links are smashed together. Some padding would help, right?
Padding spreads the links out horizontally, but where's the padding on the top and bottom? One way to debug this problem is to add a hover effect to the anchor tags. You set the background color of a hovered anchor tag by appending :hover
to its selector:
Try bringing the mouse over a navlink. Do you see the vertical padding now? It bleeds into the surrounding content. That's because the anchor tags are inline elements. Turning them into inline block elements stops the bleeding:
The text feels a little stuffy. You switch to a bigger, sans serif font, and you also remove the underlines:
That looks nice. Try changing how the navlinks are distributed by using different values for justify-content
.