Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

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.

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly โ€” Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles