Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select odd-number element only when in last position and not an only child

I need to target the last element if its odd.

Lets say I have 3 elements. I want to target the 3rd element only because its last and its odd. But if I have 1 element I dont want this rule to apply even if that in fact is odd count aswell.

1 2 3(target)

1 2 3 4 5(target)

1 2(don't target)

1(don't target)

How could I accomplish this?

So basicly I want to combine :nth-child(odd) and :not(:only-child) and only if that applies.

like image 502
Joelgullander Avatar asked Jan 20 '17 14:01

Joelgullander


People also ask

How can I select all children of an element except the last child?

When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.

Which nth child () selector will target only the last list item?

The :nth-last-child(n) selector matches every element that is the nth child, regardless of type, of its parent, counting from the last child. n can be a number, a keyword, or a formula.

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

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 .


2 Answers

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

  • odd
  • the last child
  • not an only child

It is fairly simple to combine all this:

:nth-child(odd):last-child:not(:only-child) {
    color: blue; // or whatever
}
like image 82
lonesomeday Avatar answered Nov 07 '22 02:11

lonesomeday


There are multiple 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) being equally specific to :only-child):

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

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

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

The expression 2n+3 starts matching from the 3rd child onwards, eliminating the need for :not(:only-child). (In comparison, the "odd" keyword is equivalent to 2n+1.)

like image 29
BoltClock Avatar answered Nov 07 '22 00:11

BoltClock