DEV Community

Stefan Judis
Stefan Judis

Posted on • Originally published at on

TIL: The hover media query can help to remove hover styles on touch devices (but may include false positives)

Please make sure to read to the end of the article... it was edited and it's not as easy as I first thought.

Today I followed an interesting thread on Twitter. Chris Coyier asked about use cases for the @supports rule in CSS. One reply shared a way to disable the "stuck hover states" of focusable elements.

Side note: It didn't use @supports but rather a media query to detect if the user agent has a hover supporting mechanism. But hey ... 🤷‍♂️

If you use your mobile device to browse the web regularly, you might know what I'm talking about. When you click a button, the button stays in an emulated hover state until another elements gets focus. The browsers implemented it this way to give users a way to reach a hover state.

You really shouldn't rely on hovers to build UIs. Unfortunately, the web is a messy place. There had to be a way to offer touch device users the same functionality as mouse users.

If you want to get rid of hover states on touch devices you can use the hover CSS media feature.

@media (hover: hover) { 
  a:hover {
    background: red;
    color: white;
Enter fullscreen mode Exit fullscreen mode

Personally, the hover styles are not bothering very much, but I could imagine that it annoys some people. Using this media query, you can get rid of the sticky hover state. 🎉

I set up a quick CodePen ( if you want to try it on your mobile phone.

But wait!!!

Edited: Patrick H. Lauke had some very valuable comments.

In general, don't try to "detect" touch devices. design so it works for touch/mouse/stylus/keyboard. if you must, use whatinput.js or similar to check/guess the origin of the latest event

Detecting touch devices turns out to be very very hard. There are devices like the Microsoft Surface that can have a set of input mechanism. Or what if you use a mouse with your tablet. Before you implement media queries make sure to read Patrick's recommended resources.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.