I need to select the nth child of a class not counting elements of a specific class in less. As an example, given:
li
li class="skip_this"
li
li
li
I want to make the nth-child skip the skip_this class when counting, meaning that if I wanted the 3rd li that is not skip_this, it would actually select the 4th li, because it wouldn't count the one with skip_this.
As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .
The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.
To create a CSS child selector, you use two selectors. The child combinator selects elements that match the second selector and are the direct children of the first selector. Operators make it easier to find elements that you want to style with CSS properties.
tr:nth-child(even) or tr:nth-child(2n) Represents the even rows of an HTML table: 2, 4, 6, etc. :nth-child(7) Represents the seventh element.
Use :not() like
li:nth-child(2n):not(.skip_class){
}
li:nth-child(2n):not(.skip_class){
background:green;
}
<ul>
<li>test</li>
<li class="skip_class">test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
Update
My intention is that if I wanted to select the 2nd child that is not 'skip_class', it would select the third child, since the 2nd child is a 'skip_class'
Use the immediate sibling selector +
like
li:nth-child(2n):not(.skip_class), .skip_class + :not(.skip_class)
li:nth-child(2n):not(.skip_class),
.skip_class +:not(.skip_class) {
background: green;
}
<ul>
<li>test</li>
<li class="skip_class">test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
Udpate
To make it clear, trying to target a set of elements with a condition (class) irrespective of some siblings does not work because nth-child
and nth-of-type
will target all siblings or siblings of the same type.
When you add a condition(:not(.skip_class)
), it works independently of the the other selector(nth-child
)
See Can I combine :nth-child() or :nth-of-type() with an arbitrary selector?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With