DEV Community

Cover image for Why Your :hover Selector isn't Working
Jamie Mc Manus
Jamie Mc Manus

Posted on • Edited on

5 3

Why Your :hover Selector isn't Working

The post is suitable for anyone with a basic knowledge of CSS

Have you ever tried to use the CSS hover selector but it just doesn't seem to work for you ? Or worse yet it applies to the wrong elements ?!?

If you're like me then it has happened a lot.

And for a long time I was stumped.

That is, until now.

Its in the Details

Lets take a look at an example of a hover effect:

.parent1 :hover{
  background-color:red;
}
```
{% endraw %}


You'd guess that class would change the background colour of the parent1 class to red on hover right ? 

Well you'd be wrong. 

Now take a look at this one :
{% raw %}

````css
.parent1:hover{
  background-color:red;
}
```
{% endraw %}


Would you believe that this one would change the background colour of the parent1 class to red ? 

If so, you'd be correct.

But what is the difference ?  You'd be forgiven if you can't  tell the difference - I know I didn't at first. 

It's the *space* character before the {% raw %}`:hover`. 

The space character in CSS is a [descendant combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator) ,which in this case means it will apply the hover effect to all the child elements of the element - not the element itself. 

That's a pretty big difference for such a seemingly innocuous space. 

### **Comparison**  
Take a look at the below examples to see what I mean. 

{% jsfiddle https://jsfiddle.net/nu9h2gvd/3/ result,html,css %}
The Moral of the Story ? 

**Mind The Gap !**

#### Slán go fóill
I hope this has cleared up any confusion about why your hover effects weren't working for you ! 

Feel free to ask questions, comment or contribute below!

And if you're feeling generous you can buy me a coffee with the link below ( and yes its all for coffee,  I drink a copious amount of it while writing  )  


[![Buy Me A Coffee](https://cdn.buymeacoffee.com/buttons/default-black.png)](https://www.buymeacoffee.com/SUKaQp9)
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay