The CSS focus ring is the visual indicator (usually a blue or dotted outline) that appears around interactive elements like links, buttons, and inputs when they are focused via keyboard navigation (like pressing the Tab key).
It is a critical feature for accessibility (a11y), allowing users who don't use a mouse to see exactly where they are on a page.
The CSS Focus Pseudo-Classes
To style the focus ring, you will primarily use three pseudo-classes depending on how you want the ring to behave:
:focus: Applies whenever an element receives focus, whether by keyboard, mouse click, or touch. (Can look messy when mouse users click a button and get a big ring).
:focus-visible: The modern standard. It only applies the focus ring when the browser determines it’s helpful—typically only for keyboard users, leaving mouse users with a clean interface.
:focus-within: Applies to a parent element when any of its child elements gain focus.
How to Style the Focus Ring
Historically, developers used outline, but modern CSS gives us much better control using outline, box-shadow, and outline-offset.
1. The Modern Standard (:focus-visible)
Use this for 95% of your use cases to keep things accessible for keyboard users without annoying mouse users.
CSS
/* Target buttons and links when focused via keyboard */
button:focus-visible,
a:focus-visible {
outline: 3px solid #3b82f6; /* Thicker, vibrant blue ring */
outline-offset: 2px; /* Pushes the ring away from the element */
}
2. The Custom Glow Effect (box-shadow)
If you want a smoother, curved focus ring that matches an element's border-radius, box-shadow is excellent. Note that you should always pair it with a transparent outline so users with Windows High Contrast Mode can still see it.
CSS
input:focus-visible {
outline: 2px solid transparent; /* Fallback for high-contrast accessibility */
border-color: #3b82f6;
box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.5); /* Soft outer glow */
}
3. Styling the Parent (:focus-within)
Great for form cards or search bars where you want the entire container to light up when the input inside is active.
CSS
.search-form-container:focus-within {
border-color: #10b981;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
The Golden Rule: Never Just outline: none
⚠️ Accessibility Warning: Never use outline: none or outline: 0 without immediately providing a custom, highly visible focus alternative. Removing the focus ring entirely breaks website navigation for millions of keyboard and assistive technology users.
If you hate how the default focus ring looks on mouse clicks, don't kill it completely. Just use :focus-visible instead:
CSS
/* Bad: Breaks accessibility completely */
button:focus {
outline: none;
}
/* Good: Removes default for mouse, keeps/customizes for keyboard */
button:focus {
outline: none; /* Reset default */
}
button:focus-visible {
outline: 3px solid #ff4757; /* Custom keyboard focus */
}
Cheers
Samitha
No comments:
Post a Comment