Reputation: 39
What is the difference between these two different hover selector syntaxes?
#id:hover p
#id p:hover
Upvotes: 2
Views: 80
Reputation: 89750
Both of them select the p
element which is a child or descendant of an element with id='id'
but the difference lies in when it gets selected and the no. of elements that get selected.
#id:hover p
- Here the p
gets selected when the element with id='id'
is hovered on (the parent or grandparent is hovered). This will select all the descendant p
tags.#id p:hover
- Here the p
gets selected when the p
itself is hovered (and not the parent or grandparent). This will select only the p
which is being hovered on.As you can see in the below snippet, hovering on the p
tag itself (the text Child para or Descendant para) will change the text color
to beige
only for the p
which is actually being hovered whereas hovering on the other parts (which is the parent) would change the background
of all descendant p
to red
.
You would also notice that hovering on the p
tag also causes its background
to get changed to red. This is because when p
is hovered on, the parent/grandparent is also getting hovered on implicitly.
#id:hover p {
background: red;
}
#id p:hover {
color: beige;
}
<div id='id'>
Some content
<p>Child para</p>
<p>Child para</p>
</div>
<div id='id'>
Some content (grandparent)
<div> Some content (parent)
<p>Descendant para</p>
<p>Descendant para</p>
</div>
</div>
Upvotes: 2
Reputation: 240928
#id:hover p
- will select a descendant p
element when hovering over the parent #id
element.
#id p:hover
- will select a descendant p
element (a descendant of an #id
element) when it is being hovered over.
Take this for example:
.example1:hover p,
.example2 p:hover {
color: red;
}
div {
border: 1px solid;
}
div p {
border: 1px solid #f00;
}
<div class="example1">
<p>.example1:hover p</p>
<p>The p element is styled when hovering over the parent.</p>
</div>
<div class="example2">
<p>.example2 p:hover</p>
<p>The p element is styled when hovering over the p element</p>
</div>
Upvotes: 4
Reputation: 7466
id:hover p
will select the p
element inside of the element id
when the id
gets hovered.
id p:hover
will select the p
element inside of the element id
when the p
gets hovered.
Often the result is the same but nethertheless it is a difference of which element is hovered.
Upvotes: 2