Mezo Istvan does a good job of covering the problem and a solution to it in a blog post on Mediumยน.
If you tap on something that has a :hover
state but you don’t leave the page then, on a mobile device, there is a chance that :hover
state “sticks.” You’ll see this with stuff like jump-links used as tabs or buttons that trigger on-page functionality.
button:hover {
border: 3px solid green; /* might stick! */
}
The solution, or trick, is a new(ish) “CSS4” media query that allows you only to apply styles on devices with hover capability.
@media (hover: hover) {
button:hover {
border: 3px solid green; /* solves sticky problem */
}
}
Your typical touch screen mobile device will fail that media query, the style won’t apply, and you’ll avoid the sticky problem.
Support is solid, so not much worry there.
- It almost feels like we have to apologize to linking to things on Medium lately. I have no idea what you’re going to experience when you get there. Will you just be able to read it? Will it be a teaser where you have to log in to read more? Will it be behind a paywall? I have no idea. In this case, hopefully, this link post has enough info in it that isn’t not blocking you from learning anything.
Love the concise nature of this article.
And regarding the footnote, thanks for adding that.
I personally think articles like these should not be a medium (pun intended) of monetization.
It is also one of the reasons I like to come here more often.
Unfortunately this time for me I had to log in to Medium to continue reading. Thanks for the summary here!
The idea is awesome but it doesn’t work on my phone (android 9) with Chrome 80.
tested it with the following code:
@media (hover: hover) {
html,body{
background:red !important;
}
}
Also test it on https://developer.mozilla.org/en-US/docs/Web/CSS/@media/hover
Both failed
This will sound silly but why do :hover styles even take effect on touch screens in the first place if they fail the media query check?
I second Jamie’s question. If a browser decides that it should fail the hover media query, why would it acknowledge :hover psuedo-classes? Can anyone think of a use case where a browser would want to fail one but not the other?
That’s neat. I hadn’t come across this media query before.
Previously, I’ve used https://github.com/ten1seven/what-input to manage
:hover
and:focus
styles based on input type.If you need to support IE11 check out this solution: https://stackoverflow.com/a/55867559
I think this way might be simpler: