loading...

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

stefanjudis profile image Stefan Judis Originally published at stefanjudis.com on ・2 min read

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;
  }
}

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 (www.my-links.online/hover-states/) 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.

Posted on by:

stefanjudis profile

Stefan Judis

@stefanjudis

DevRel at Contentful. In love with web performance, new technologies, and accessibility – all the good stuff ✌️.

Discussion

pic
Editor guide
 

This article is pretty useful. I find hover states a bit annoying sometimes. I collect reviews and tips about online casinos and you could check here on the internet to get more information regarding online casinos. Next time when I will be working on my touch phone I will use the hover CSS feature to get rid of hover states. Hopefully, it will work.