Select an odd-numbered element only in the last position, and not in a single child

I need to target the last item if it's odd.

Let's say I have 3 elements. I want to target the third element only because its last and odd. But if I have 1 element, I do not want this rule to apply, even if it is really an odd number.

1 2 3(target) 1 2 3 4 5(target) 1 2(don't target) 1(don't target) 

How could I do this?

Basically I want to combine :nth-child(odd) and :not(:only-child) and only if applicable.

+6
source share
3 answers

I think you mean you want to select an element if it

  • odd
  • last child
  • not the only daughter

Simply combine all of this:

 :nth-child(odd):last-child:not(:only-child) { color: blue; // or whatever } 
+10
source

There are several ways to do this with varying degrees of specificity in case it matters to you.

One, as already suggested by lonesomeday, with specificity (0, 3, 0) (3 pseudo-classes, with :not(:only-child) equally specific for :only-child ):

 :nth-child(odd):last-child:not(:only-child) 

Another, with specifics (0, 2, 0):

 :nth-child(2n+3):last-child 

The expression 2n + 3 begins to match the third child ahead, eliminating the need for :not(:only-child) . (For comparison, the keyword "odd" is 2n + 1.)

+5
source

If you do magic, you may not use it as a selector

 target:not(:first-child):last-child { /*some magic css*/ } 
-2
source

Source: https://habr.com/ru/post/1014255/


All Articles