Sub topic 5
Style hover and keyboard focus states
A navigation bar needs to respond to the reader. Mouse users expect a link to change when the pointer is over it. Keyboard users need to see which link they are on as they press Tab. This chapter covers both, and the differences between them cause most of the common mistakes.
Prerequisites
This chapter assumes you can read basic HTML and CSS, know the box model, and have the navigation bar from the earlier chapters. That bar is a nav element holding a ul of links. The list styles are reset, the list is a flex row, and each link is display: block with padding. If you skipped those chapters, here is the starting point.
<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>.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;
}With this CSS the links look the same in every state. You will add the states in the sections below.
The states a link can be in
A link is not a single visual state. The browser tracks several conditions at once and exposes each one as a CSS pseudo-class. A pseudo-class is a keyword added to a selector that matches an element only while some condition is true.
| Pseudo-class | Matches when | Typical use in a nav bar |
|---|---|---|
| `:hover` | A pointer is over the element | Background change |
| `:focus` | The element has keyboard focus, however it got it | Rarely styled on its own |
| `:focus-visible` | The element has focus and the browser decides a focus indicator is helpful | Visible outline |
| `:active` | The element is being pressed | Pressed-down feedback |
Focus is the browser's record of which element receives keyboard input. A link receives focus when the reader presses Tab to reach it, or when they click it. Only focusable elements can have focus. Links with an href, buttons, and form fields are focusable by default. A div is not.
Add the hover and focus styles
The simplest version gives hover and keyboard focus the same background. Then focus gets an extra outline.
.nav-list a:hover,
.nav-list a:focus-visible {
background: #374151;
}
.nav-list a:focus-visible {
outline: 2px solid #38bdf8;
outline-offset: -2px;
}Sharing a background means a keyboard user sees the same highlight a mouse user does. The outline is the cue that cannot be missed. Mouse users see only the background change.
Why `:focus-visible` and not `:focus`
If you style :focus, the style also appears when someone clicks a link with a mouse. Designers often dislike the ring appearing after a click, and the usual response is to remove it. That response breaks keyboard navigation.
:focus-visible solves the problem. The browser applies it when it judges that the user needs to see where focus is. After a keyboard action such as Tab, the pseudo-class matches. After a mouse click on a link, it usually does not. You get an outline for keyboard users and a clean look for mouse users, with no script.
Do not rely on that heuristic being identical everywhere. Browsers differ in some cases. For example, focus that your script moves after a keyboard action will show the indicator, and focus that your script moves after a click may not. Test with the keyboard in the browsers you support.
Why a negative `outline-offset`
By default an outline is drawn outside the element's border box. In a flex row with a background, an outer outline on the first and last links can be clipped by a parent that has overflow: hidden, and it can collide with a neighbor. Setting outline-offset: -2px draws the outline inside the link's box, so it can't be clipped and does not overlap other links. The padding from the previous chapter keeps the text clear of it.
Outlines do not change layout. They are painted over the surrounding content without taking up space. This is why you use an outline for focus. A border would add to the element's size and make the bar shift as focus moves.
Hover is not available everywhere
Touch screens have no pointer to hover with. Many mobile browsers emulate hover when you tap: the :hover style applies and then stays on the tapped element until you tap elsewhere. In a nav bar, that can leave one link looking highlighted after the reader has already moved on to the new page.
You can limit hover styles to devices that really support hover with the hover media feature.
@media (hover: hover) {
.nav-list a:hover {
background: #374151;
}
}
.nav-list a:focus-visible {
background: #374151;
outline: 2px solid #38bdf8;
outline-offset: -2px;
}Here (hover: hover) is true when the main input device can hover, as a mouse can. The focus rule sits outside the media query because keyboards exist on every kind of device. Note that you have to split the combined selector. If you left :focus-visible inside the media query, a keyboard user on a touch laptop would lose their indicator.
Show press feedback with `:active`
:active matches while the link is being pressed, between mouse-down and mouse-up. It is useful for a small confirmation that the click registered.
.nav-list a:active {
background: #111827;
}This rule interacts with the order of your other rules. Two rules of equal specificity are resolved by source order, and the later one wins. If :active came before :hover, then while the reader presses a hovered link, :hover would win and the press feedback would never show. The traditional order for link states is :link, :visited, :hover, :focus, :active. The easy way to remember it is "LoVe HAte". Put :active last and you avoid the problem.
The current-page rule from the next chapter also affects this. A selector such as .nav-list a[aria-current="page"] has higher specificity than .nav-list a:hover. Hover then loses on the current link, and the link will not appear to respond. Often that is acceptable, because the reader is already on that page. If you want a hover response there as well, write a combined rule that includes both conditions.
Smooth the change with a transition
A transition animates a property from its old value to its new one over a set time. A short transition on the background makes hover feel less abrupt.
.nav-list a {
display: block;
padding: 0.75rem 1rem;
color: #ffffff;
text-decoration: none;
transition: background-color 150ms ease-out;
}
@media (prefers-reduced-motion: reduce) {
.nav-list a {
transition: none;
}
}Put the transition on the base state, not on :hover. If you put it on :hover, the animation runs when the pointer enters but not when it leaves, so the background snaps back. Keep the duration around 100 to 200 milliseconds. Anything longer makes the bar feel sluggish.
The prefers-reduced-motion query matches when the reader has asked their operating system to reduce animation. A color fade is mild, but turning it off for those readers costs nothing.
Make the indicator easy to see
A focus indicator has to be noticed, not only present. Two checks matter:
- Contrast. WCAG 2.2 asks for a contrast ratio of at least 3:1 between the indicator and the colors next to it. The sky-blue
#38bdf8outline against the#1f2937bar is well above that. If you change the theme colors, check the new pair with a contrast checker. - Not color alone. The hover change here is a background shift between two dark grays. That is subtle, and some readers will miss it. If you want a stronger cue, add a second signal such as an underline.
.nav-list a:hover {
text-decoration: underline;
text-underline-offset: 0.35em;
}This matters most in forced colors mode, such as Windows High Contrast. In that mode the browser replaces your colors with a small system palette and drops most background changes. Your hover background disappears, but the outline remains. That is another reason to use outline for focus rather than something such as box-shadow, which the browser also removes in that mode.
Common mistakes
- Styling only
:hover. Keyboard users get no feedback. Always pair it with:focus-visible. - Removing the outline for looks. Replace it instead of deleting it.
- Styling
:focusand then hiding it for mouse users with script.:focus-visiblealready does this natively. - Putting the hover style on the
liinstead of thea. Theliis not focusable, so the keyboard never triggers it. Theais also the element that is clickable, so the highlight should match that area. - Changing size on hover. Adding a border or padding on
:hovershifts the other links. Useoutlineor abox-shadowthat does not change layout, or reserve the space with a transparent border in the base state. - Rules in the wrong order. If a state does not show, check specificity and source order first.
Putting it together
This is the finished set of state rules for the bar, in an order that avoids the conflicts above. It extends the base CSS shown at the start.
.nav-list a {
transition: background-color 150ms ease-out;
}
@media (hover: hover) {
.nav-list a:hover {
background: #374151;
}
}
.nav-list a:focus-visible {
background: #374151;
outline: 2px solid #38bdf8;
outline-offset: -2px;
}
.nav-list a:active {
background: #111827;
}
@media (prefers-reduced-motion: reduce) {
.nav-list a {
transition: none;
}
}Add these rules after the base .nav-list a rule in your stylesheet. The last rule of each state comes after the earlier ones, so press feedback is not overridden.
Exercise
A teammate styles the nav with .nav-list a:hover { background: #374151; } and .nav-list a:focus { outline: none; }. Name two problems this causes for keyboard users and give the fix.
Show answer
First, keyboard users get no hover-style highlight, because :hover only responds to a pointer. Second, outline: none removes the default focus ring with nothing in its place, so a user pressing Tab cannot see which link is focused. The fix is to select :focus-visible alongside :hover for the background, and to give :focus-visible its own visible outline, for example outline: 2px solid #38bdf8; outline-offset: -2px;.
Exercise
You wrap .nav-list a:hover, .nav-list a:focus-visible { background: #374151; } in @media (hover: hover) { ... }. A reader on a touch laptop tabs through the bar with the keyboard. What do they see, and how do you fix it?
Show answer
On a device where the primary input cannot hover, the media query is false, so neither rule applies. The reader sees no background change when they tab, because the :focus-visible selector was inside the query. The fix is to keep only .nav-list a:hover inside @media (hover: hover) and place the :focus-visible rule outside it, so keyboard focus is styled on every device.
Exercise
Why should the transition property be on .nav-list a rather than on .nav-list a:hover?
Show answer
A transition applies when the element changes into the state that declares it. If it is declared only on :hover, the background fades in when the pointer enters, but when the pointer leaves, the base state has no transition, so the background snaps back instantly. Declaring it on the base rule animates the change in both directions.