Conditional Hover Styles in CSS

by Matt Fantinel
12 Feb 2023 - 2 min read
Laptop and phone side by side

Have you ever crafted a nice hover effect for an element in your website, then opened it on mobile and saw that effect erroneously appear when that element is tapped on? That’d be nice perhaps, if it weren’t for the fact that the effect just… stays there.

That happens because touch-based browsers apply the hover effect to an element when it’s tapped on regardless of hover capabilities and keep that effect active until you tap something else. Why do they do this? My guess is backwards compatibility, as many websites built with a mouse cursor in mind can hide important information behind a hover action, like for example displaying a tooltip.

Luckily, if you want to avoid having the hover effect applied when it shouldn’t be (and instead using :focus and :active selectors properly), there’s a CSS media query to help with that:

css
@media (hover: hover) {
	.my-component {
		/* Styles here */
	}
}

If you wanna do the opposite (add styles only to devices that do not support hover), you can use hover: none instead:

css
@media (hover: none) {
	.my-component {
		/* Styles here */
	}
}

And there you go! This is a nice thing to keep in mind whether you build mobile-first or desktop-first, as adding that media query to hover styles at the same time you're developing the styles themselves will avoid any unintended effects.

Written by

Matt Fantinel

I’m a web developer trying to figure out this weird thing called the internet. I write about development, the web, games, music, and whatever else I feel like writing about!

About

Newsletter? I have it!

I have a newsletter as another way to share what I write on this blog. The main goal is to be able to reach people who don't use RSS or just prefer getting their articles delivered straight into their inbox.

  • No fixed frequency, but at least once at month;
  • I do not plan on having content exclusive to the newsletter. Everything on it will also be on the blog;
  • I will never, ever ever ever, send you any form of spam.

You might also like

View blog

Setting up Storybook on an Astro project

7 min read

I really, really thought this was gonna be easy.

Front-End
Read

Automating Social Media Preview Images

6 min read

Social media preview images are very useful if you want to attract people to your website. They're sometimes a pain to create, though. Let's automate it!

Front-End
Read

Progressive Enhancement (and why it matters)

8 min read

Progressive Enhancement isn't just another web jargon; it's a guiding principle shaping modern web development.

Front-End
Read

“Classic rock, Mario Kart, and why we can't agree on Tailwind”

1 min read

Great article from Josh Collinsworth explaining why Tailwind is good and bad for the exact same reasons.

Reading Recs
Read