Hone

Lessons · HTML and CSS · :hover and :focus

:hover and :focus

A pseudo-class selects a state: :hover while the pointer is over an element, :focus while it has keyboard focus. Style both together, and a transition makes the change ease.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Feedback is what makes a page feel alive, and keyboard users get none of it from :hover alone. Pairing the two is the habit that keeps a site usable without a mouse.

How to think about it

Write the resting style, then one rule for :hover and :focus together. Add a short transition on the property that changes.

Worked example

<a href="/docs" class="btn">Docs</a>
A link styled as a button.
.btn { color: rgb(0, 0, 200); transition: color .2s; }
The resting state, and a transition so the colour change eases over 0.2 seconds.
.btn:hover, .btn:focus { color: rgb(200, 0, 0); }
While the pointer is over it, or it has keyboard focus: both, so keyboards are not left out.

Your turn

Style the link while the pointer is over it.

a: { text-decoration: underline; }

The trap

outline: none on :focus to tidy up a hover effect. It removes the only sign a keyboard user has of where they are. Style the focus ring; never delete it.

Practise :hover and :focus on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.