Tired of focus styles applying on mouse clicks? :focus-visible is the trick. - Exotic Digital Access
  • Kangundo Road, Nairobi, Kenya
  • support@exoticdigitalaccess.co.ke
  • Opening Time : 07 AM - 10 PM
Tired of focus styles applying on mouse clicks? :focus-visible is the trick.

Tired of focus styles applying on mouse clicks? :focus-visible is the trick.

Having focus styles for any interactive element is crucial on a website. Hidde de Vries:

Focus indicators make the difference between day and night for people who rely on them. […]

Focus outlines help users figure out where they are on a page. They show which form field is currently filled in, or which button is about to be pressed. People who use a mouse, might use their cursor for this, but not everyone uses a mouse. For instance, there are many keyboard users: a person with a baby on one arm, people with chronic diseases that prevent the use of a mouse, and of course… developers and other power users.

You don’t have to create your own :focus styles in CSS, although you can. By default, browsers apply their own styles to interactive elements. But if you don’t like that look, the temptation is to style your own. So if you do something like this, boom, we’ve got focus styles under our control:

button:focus {
  outline: 5px solid red;
}

(By the way, outline is a great friend to focus styles for reasons Manuel Matuzovic gets into.)

But by doing this, we’ve also done something else: we’ve made it so when you click (like with a mouse on a desktop computer, otherwise known as a fine pointer) those :focus styles apply to the element. This can be highly undesirable, leading to the CEO being all like why does the button change looks when I click it??? Fair enough, CEO, let’s fix it.

The trick is using :focus-visible which is relatively new but has pretty solid browser support. The whole point of it is applying focus styles that apply at all times an element takes focus, except when a fine pointer clicks it. Which is kinda perfect really. But if you’re nervous about going all-in on only using :focus-visible, a way to continue to use :focus styles too is to wrap them in an @supports block like:

@supports not selector(:focus-visible) {
    button:focus {
        
    }
}

Fortunately, the browser support for @supports and the selector() function is a bit better than :focus-visible, so this buys some additional browser support Tired of focus styles applying on mouse clicks? :focus-visible is the trick..

Pen:

CodePen Embed Fallback

The post Tired of focus styles applying on mouse clicks? :focus-visible is the trick. appeared first on CodePen Blog.


Source link

Leave a Reply