How To Apply CSS Hover To Desktop Only And Avoid Changes To Mobile

Arturo Lopez

October 2, 2024

How To Apply CSS Hover To Desktop Only And Avoid Changes To Mobile

How To Apply CSS Hover Effect To Desktop Only And Avoid Changes To Mobile

What is CSS Hover?

Are you a web developer working on applying a CSS animation or styling effect on a “hover”?

The :hover selector allows you to change the styling of an item when a user hovers over it.

Here is the syntax:

:hover {

  css declarations;

}


For example:

/* mouse over link */

a:hover {

  color: red;

}

W3 Schools describes it as: “The :hover selector is used to select elements when you mouse over them.”

The Problem and Solution

The problem for me was that it was also registering a hover when a user would touch the component on their phone. But I didn’t want any changes to happen on the mobile screen.

I spent way too much time trying to figure out how to apply my css class to desktop/laptop (while leaving the mobile unchanged), so I am writing a quick article for anyone who may be struggling with the same thing.

Here is my solution in code.

This is what I did to fix it:

I changed this:

a:hover {

 background-color: green;

 color: white;

}

to this:

@media (hover: hover) {

 a:hover {

 background-color: green;

 color: white;

}

}

And that's it! That's what did it for me.

CSS can be tricky sometimes, but can also be a lot of fun.

I hope this helps!

<All Posts