Here's a dummy piece of code as an example :
<div id="parent">
<div class="child" id="childA"></div>
<div class="child" id="childB"></div>
<div class="child" id="childC"></div>
</div>
I am trying to style the children when hovering their parent. Except, I want to do so with the nth-child selector.
I can make what I want with this syntax :
#parent:hover #childA {
/* styling stuff */
};
But everything break when I try to use this one :
#parent:hover #parent:nth-child(1).child {
/* styling stuff */
};
Note that doing so
#parent:nth-child(1).child {
/* styling stuff */
};
Does indeed apply the style to #childA
Thus, my question is :
Why using #parent:nth-child(1).child
doesn't capture #childA to apply style (when put after #parent:hover
), and how can I fix this behaviour ?
I already tried all selector combination that I could think of but nothing happened. (+, >, blank, ~, getting rid of the .child at the end, chaining the :hover:nth-child(), ...)
I also reviewed all questions already asked on the subject I could find, but no one seems to have wrote about this specific use-case.
To be clear : My problem only occur when using nth-child after :hover.
The nth-child
pseudo-class applies to the element it's attached to, not to its children. When you write #parent:nth-child(1)
, you're referring to #parent
itself being the first child of its parent, not to the first child of
#parent`.
#parent:hover .child:first-child {
/* styling stuff */
}
#parent:hover > div.child:nth-child(1) {
/* styling stuff */
}