Reputation: 63647
Is there a CSS selector that can select the nth-child
, but counting from the last element?
I want to set the color of the 2nd to last element as red, but the number of <p>
elements is variable.
Example:
<div>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
</div>
Upvotes: 1
Views: 103
Reputation: 12974
Try:
div > p:nth-last-child(2) {color: red}
It starts counting backwards from the last p
, so div > p:nth-last-child(3)
would set the colour of the 3rd last p
tag.
Upvotes: 0
Reputation: 2896
It is called nth-last-child(2)
. It is the same thing as nth-child
, but it is starting from the bottom of the list of items instead of the top.
From MDN:
The :nth-last-child CSS pseudo-class matches an element that has an+b-1 siblings after it in the document tree, for a given positive or zero value for n, and has a parent element
Upvotes: 1
Reputation: 723688
That would be p:nth-last-child(2)
, rather than p:nth-from-last-child(2)
.
Upvotes: 1