DEV Community

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

Posted on • Updated on

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

Top comments (0)