Vedant Terkar
Vedant Terkar

Reputation: 4682

Is there any difference between "element:hover" and "element :hover"

I was testing a JQuery code for dynamically appending :hover Css to <head>.

and I've found that there is difference in working of element :hover and element:hover (Note The Space)

That is, When I change CSS of :hover dynamically using JQuery like:

$(document).ready(function(){
$("head").append("<style type='text/css'> 
                  .nav_menu li :hover{
                       background-color: red !important; 
                    } 
                   </style>");  // Code is formatted and trimmed for simplicity.
});


FULL CODE
If the Initial CSS has element :hover then it works fine.

That is If initial CSS is:

.nav_menu li :hover{
    background:#a55;
    color:#fff;
}

Then every thing works fine, and the output is like:

"Initial Working output"

Also you can see it Here.


But if initially CSS is like element:hover that is:

.nav_menu li:hover{
    background:#a55;
    color:#fff;
}

Then weird padding of initial background color occurs after hovering the element.

like:

"Weird Behaviour"

As you can see this version of element:hover doesn't work as expected. Fiddle.

Also initial styling isn't rendered correctly in this.


So it is obvious and clear that there is difference between element :hover and element:hover (Note Space (&nbsp;)). or is it my browsers fault? tested it on chrome and firefox; same issue on both.

Can experts here, please clear this to me? thanks in advance.

PS:

I dont want to use a:hover in fact I'm here to know why is this happening.

Upvotes: 0

Views: 96

Answers (3)

aniskhan001
aniskhan001

Reputation: 8521

YES! There is a difference.

element:hover applies to the element itself when it's in the hover state.
element :hover applies to child elements of that element when any of them are in the hover state.

Upvotes: 2

GGio
GGio

Reputation: 7653

There is a big difference. Its same as element .div-class and element.div-class. The second one will select .div-class that is the class of element, First one will select .div-class that is the child of element

Upvotes: 2

Richard Deeming
Richard Deeming

Reputation: 31198

Yes, there is a difference:

  • element:hover applies the rules to the element when it is in the "hovered" state;
  • element :hover applies the rules to descendants of the element when they are in the "hovered" state.

Upvotes: 3

Related Questions