How to Select the Second Last Child in CSS?

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:

   <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>

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:

Select the second last child in CSS

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:

Select second last list item in CSS

Thanks for reading.


  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts