To select the second last child of an element, you can use the :nth-last-child(N)
selector. The :nth-last-child() selector allows you to select the nth child of its parent but counting from the last.
For example, if you pass an integer value 1 into the :nth-last-child()
selector, it will select the last child. Similarly, an integer value 2 will select the second last child of its parent element.
Let’s say we have a div element with several child paragraphs and we want to select and highlight only the second last child paragraph:
<div> <p>This is the first child</p> <p>This is the second child</p> <p>This is the third child</p> <p>This is the second last child</p> <p>This is the last child</p> </div>
To select the second last paragraph, we have to pass an integer value 2 into the :nth-last-child()
selector.
Something like this:
/*Select second last paragraph*/ div p:nth-last-child(2){ background: yellow; }
This will be the output after applying the above styles:
You can apply this concept to any HTML element.
For example, selecting the second last list item in an unordered list:
/*Select second last list item*/ ul li:nth-last-child(2){ background: yellow; }
This will be the output:
Thanks for reading.