Aspizu's avatar
Sunday 07 July 2024 09:59:24 PM IST

Avoid :focus-visible

:focus is a pseudo-class that is used to style elements that are focused. Either by clicking on them with the mouse, or by tabbing to them with the keyboard. Having a outline around buttons and links isn’t the most visually appealing thing, so people often remove it. To solve this, the :focus-visible pseudo-class was introduced. But it still doesn’t solve the problem.

You should always have a focus style for elements which can be activated with the keyboard either by pressing space or enter.

:focus-visible is a pseudo-class that is used to style elements which were focused by keyboard input. (This isn’t exactly how it works, thats another issue with it.)

So if you have removed the default focus otuline on a button, and have added the outline on :focus-visible, you won’t have a outline when the user clicks on the button. But the focus is still moved to that button. This creates a scenario where there is no visual indicator that the button is focused, but pressing Enter will click the button.

Look at this button, click it once, then press Enter.

Notice there is no way for you to know what will happen when you press Enter.

Now, do the same with this button.

You might say this isn’t really a big issue for things like buttons and links because usually clicking them changes the view or focuses something else. A button which opens a modal will focus the modal. Closing the modal will set :focus-visible for the button.

But this is a problem for form elements such as dropdowns, checkboxes, etc. and for buttons and links which don’t move focus away from them or change views.