DEV Community

Cover image for The Correct :hover
Misha
Misha

Posted on

The Correct :hover

If you're styling hover with CSS, I have some news for you.

THERE IS NO HOVER ON TOUCHSCREENS!

Why? Well, because hover is the state of an element over which a pointer (mouse cursor) is placed. Obviously, a smartphone does not know over which element a user's finger is hovering.

I don't what was the logic behind it, but for some reason mobile browser developers decided to enable hover styles when tapping on an element. The problem is that tapping on an element on a touchscreen leads to the styles hanging in a hover state.

What it looks like: the user taps a button, and it starts glowing as if a cursor has been placed over it. And this state is maintained until the next tap or scroll​​.

What to do?

There are Interaction media features in CSS. It's a media query that determines whether a user can hover over elements and whether they use a precise (mouse or stylus) or imprecise (finger) pointer. Example:

/* smartphones, touchscreens */
@media (hover: none) and (pointer: coarse) { /* ... */ }

/* stylus-based screens */
@media (hover: none) and (pointer: fine) { /* ... */ }

/* Nintendo Wii controller, Microsoft Kinect */
@media (hover: hover) and (pointer: coarse) { /* ... */ }

/* mouse, touch pad */
@media (hover: hover) and (pointer: fine) { /* ... */ }
Enter fullscreen mode Exit fullscreen mode

If you're using SCSS, please write yourself a mixin.

And if you're using Tailwind 3+ just go to your config and set hoverOnlyWhenSupported to true:

// tailwind.config.js
module.exports = {
  future: {
    hoverOnlyWhenSupported: true,
  },
  // ...
}
Enter fullscreen mode Exit fullscreen mode

If you like the article, please hit reactions and subscribe.

Also follow me on Twitter, connect on LinkedIn.

Top comments (0)