Enable hover conditionally in CSS
Setting up hover on elements in devices where hover is not supported (like mobiles, tablets…) can be overkill. For instance, if you have a navigation menu that has a hover effect on a desktop browser, you might want to disable that hover effect on mobile devices because there’s no hover support on mobile devices.
So, how do you do that? Well, today I learned, you can do that using the @media
query and the any-hover
media feature.
Essentially, the any-hover
media feature is a media query that returns true
if the device supports hover and false
if it doesn’t. So, you can use this media query to disable hover on devices that don’t support it.
Here’s how you can do it.
@media (any-hover: hover) {
.nav-item:hover {
background-color: #ccc;
}
}
So, now, the hover effect will only be enabled on devices that support it. And on devices that don’t support it, the hover effect will be disabled.
The feature is also widely supported on most modern browsers. You can check the support table here.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.