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.
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.
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.
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 .
I think you mean you want to select an element if it
It is fairly simple to combine all this:
:nth-child(odd):last-child:not(:only-child) {
color: blue; // or whatever
}
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.)
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