How to Style CSS Focus Outline
Published Mar 28, 2021
Table of Contents
- Default Styles Donât Spark Joy
- Removing Focus Outline Is Bad For Accessibility
- Outline Doesnât Work for Rounded Corners
- Using Border Causes Layout Shifts
- Use Box Shadow
- Conclusion
Default Styles Donât Spark Joy
Do you ignore focus styles because theyâre ugly? Iâm going to explain why you shouldnât remove them, and show you how to style them to match your UI (user interface) instead.
Letâs say youâre presented with the design above. If you were to just Tab through, itâs functional â but we can agree itâs not something to behold.
Removing Focus Outline Is Bad For Accessibility
You might be tempted to remove focus styles. Thereâs only one problem. Itâs terrible for accessibility. Focus outline provides visual feedback for users who canât use a mouse, or have visual impairment, when using Tab on their keyboard for navigation.
/* đŤ don't do this */
:focus {
outline: none;
}
Be mindful that impairment doesnât only refer to people with permanent disabilities. You can have temporary impairment due to injury, so the number of people with impairments is higher than you might think.
Itâs our responsibility to make the web accessible for everyone.
Outline Doesnât Work for Rounded Corners
/* â ď¸ doesn't work for rounded corners */
:focus {
outline: 3px solid hsla(220, 100%, 50%, 80%);
}
There is no way of specifying a border radius for outline at the moment, other than some browser specific experimental features.
Using Border Causes Layout Shifts
/* đŤ don't do this */
:focus {
outline: none;
border: 3px solid hsla(220, 100%, 50%, 80%);
}
The layout shifts from the border cause our elements to jump around. It can probably be solved by setting a border on each element with no opacity, and then bring the opacity back on focus. I donât hate this idea, but itâs not great.
Use Box Shadow
/* â
do this */
:focus {
outline: none;
box-shadow: 0 0 0 3px hsla(220, 100%, 50%, 80%);
}
This works for any focusable element. Not only does it take on the same rounded corners, but you can control other properties such as color, opacity, offset, and blur. You can read more about box-shadow here.
Notice weâre also able to animate the transition.
.element {
transition: box-shadow 0.3s ease;
}
Conclusion
Accessibility is important. Itâs an important subject worth understanding. No one goes out of their way to create a bad user experience on purpose. If youâre aware, and strive to make the web a better place â thatâs what counts.