Focus and accessibility
Keep your pages usable for everyone with a visible focus state and readable contrast.
- Add a clear, visible :focus-visible style for keyboard users.
- Explain why removing an outline without a replacement breaks accessibility.
- Check text and background contrast so content stays readable.
- Use prefers-reduced-motion to reduce animation for those who need it.
In plain English
Focus is the browser way of showing which element a keyboard or screen reader user is currently on, and it is usually drawn as an outline. The :focus-visible pseudo-class shows a focus ring only when the user is navigating by keyboard, so mouse users do not see it. Removing the outline without adding a replacement makes a page unusable for people who cannot use a mouse. Accessibility also means enough contrast between text and background, plus respecting prefers-reduced-motion for people sensitive to movement.
Step by step
- 1Press the Tab key and watch the focus outline move between links and buttons.
- 2Style :focus-visible so the ring is bold and easy to see.
- 3Compare the text colour against its background to check the contrast.
- 4Add a prefers-reduced-motion block that turns off animations for users who ask for it.
button {
outline: none;
}
button:focus-visible {
outline: 3px solid #2563eb;
outline-offset: 2px;
}
.card {
background: #ffffff;
color: #1f2937;
}
@media (prefers-reduced-motion: reduce) {
* {
animation: none;
transition: none;
}
}Common mistakes
- Beginners often write outline: none everywhere to make things look clean and accidentally lock out keyboard users.
- A common mistake is relying on colour alone to show state, which is invisible to colour-blind users.
- Low contrast between text and background is a frequent error that makes small text unreadable.
- Forgetting prefers-reduced-motion means some users get dizzy from animations they cannot turn off.
Add a visible keyboard focus ring
Style buttons so keyboard users see a clear focus ring without affecting mouse clicks.
button {
padding: 0.75rem 1.25rem;
}When does :focus-visible apply by default?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.