Update 2021-01-28: Nowadays we can use :focus-visible
for this; No JavaScript needed!
David Gilbertson:
You click a button and see a blue border telling you that you’ve clicked on something that you know perfectly well you’ve just clicked on — because you just clicked on it.
So it’s clear: the outline must go.But hold on a minute, what about those users that don’t/can’t use a pointing device? They might be tabbing around the page to focus particular elements — and now they can’t tell which element is currently focused.
With the help of a little JavaScript the focus ring can be added when TAB’ing. The moment a user hits tab, the class user-is-tabbing
is added to the body. Taking (the lack of) that class into account, one can hide the focus ring when the user is not tabbing:
body:not(.user-is-tabbing) button:focus,
body:not(.user-is-tabbing) input:focus,
body:not(.user-is-tabbing) select:focus,
body:not(.user-is-tabbing) textarea:focus {
outline: none;
}
With some more JavaScript on could again remove the user-is-tabbing
class from the body from the moment the user starts clicking around again.