The :Nth-Last-Child(n) Pseudo-Class

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. The 'n' can be a number, a keyword, or a formula. In this example, the selector specifies a background color for every <p> element that is the second child of its parent, counting from the last child:


HTML file: Displayed by browser:

<style>
p:nth-last-child(2) {
    background: #ff0000;
}
</style>


<body>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</body>

The first paragraph.

The second paragraph.

The third paragraph.

The fourth paragraph.

This is the same as using :nth-last-of-type() selector to select the element that is the nth child, of a specified type, of its parent, counting from the last child. Note: Internet Explorer 8 and earlier versions do not support the :nth-last-child() selector.

Back button Table of Contents Next button