Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nth-child skipping over specific class less

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.

like image 570
Ofek Gila Avatar asked Jun 18 '15 20:06

Ofek Gila


People also ask

What's the difference between the nth of type () and Nth child () selector?

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 .

What is the nth child () selector used for?

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.

Which is are the correct way s to select child 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.

What does TR nth child even mean the style here will be?

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.


1 Answers

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?

like image 76
AmmarCSE Avatar answered Oct 29 '22 12:10

AmmarCSE