Styling Links with CSS
When styling links, it's important to understand how pseudo-classes are used to style the different states a link can be in.
- link (unvisited) – the default state of a link,
- visited – the link is already in the browser history,
- hover – when the mouse cursor is over a link,
- focus – a link selected by the user when navigating with the Tab key
or focused programmatically using
HTMLElement.focus(), - active – a link in an active state, when the user clicks on it.
Observations about the default state of links:
- they are underlined,
- unvisited links are blue,
- visited links turn purple,
- hovering the mouse cursor over a link changes the cursor icon,
- if selected with the Tab key, a visible outline appears,
- active links are red – you can see this if you click a link without releasing the mouse button.
These characteristics are almost identical to those from the early browsers of the '90s and have been retained to avoid confusing users. For this reason, link styling shouldn't deviate too far from familiar behavior.
In this regard, use underlining for links and not for other elements. If you prefer not to underline, highlight links in another way. Provide users feedback in the hover and focus states that slightly differs from the active state.
The default styling can be removed or modified using the following properties:
- color
- cursor
- outline
To style links, we can use the properties above plus many others, as we'll see in the following examples.
To start, we'll write a series of empty rules in the correct order:
a {
}
a:link {
}
a:visited {
}
a:focus {
}
a:hover {
}
a:active {
}
This order is important because the states are built on top of each other. Declarations in the first rule will apply to all subsequent ones, and activating a link primarily requires the mouse pointer to be over it.
Links with Icons
Including icons alongside links is a common practice, and they serve to indicate what type of content the links point to.
Button-style Links
The tools explored so far can also be used in other ways. For example, the hover state can be used to style many different elements, not just links.
Often, links are designed to look and behave like buttons – for instance, a navigation menu built from a list containing links that provide users access to other pages on the site that might otherwise be inaccessible.
