I want to ignore all :hover
CSS declarations if a user visits our website via touch device. Because the :hover
CSS does not make sense, and it can even be disturbing if a tablet triggers it on click/tap because then it might stick until the element loses focus. To be honest, I don't know why touch devices feel the need to trigger :hover
in first place – but this is reality, so this problem is reality as well.
a:hover {
color:blue;
border-color:green;
// etc. > ignore all at once for touch devices
}
So, (how) can I remove/ignore all CSS :hover
declarations at once (without having to know each one) for touch devices after having them declared?
Best Answer
tl;dr use this: https://jsfiddle.net/57tmy8j3/
If you're interested why or what other options there are, read on.
Quick'n'dirty - remove :hover styles using JS
You can remove all the CSS rules containing
:hover
using Javascript. This has the advantage of not having to touch CSS and being compatible even with older browsers.Limitations: stylesheets must be hosted on the same domain (that means no CDNs). Disables hovers on mixed mouse & touch devices like Surface or iPad Pro, which hurts the UX.
CSS-only - use media queries
Place all your :hover rules in a
@media
block:or alternatively, override all your hover rules (compatible with older browsers):
Limitations: works only on iOS 9.0+, Chrome for Android or Android 5.0+ when using WebView.
hover: hover
breaks hover effects on older browsers,hover: none
needs overriding all the previously defined CSS rules. Both are incompatible with mixed mouse & touch devices.The most robust - detect touch via JS and prepend CSS :hover rules
This method needs prepending all the hover rules with
body.hasHover
. (or a class name of your choice)The
hasHover
class may be added usinghasTouch()
from the first example:However, this whould have the same drawbacks with mixed touch devices as previous examples, which brings us to the ultimate solution. Enable hover effects whenever a mouse cursor is moved, disable hover effects whenever a touch is detected.
This should work basically in any browser and enables/disables hover styles as needed.
Here's the full example - modern: https://jsfiddle.net/57tmy8j3/
Legacy (for use with old browsers): https://jsfiddle.net/dkz17jc5/19/