Home

Select the Last n Children in CSS

Sometimes you need to target more than just the last child in a series of HTML elements. Learn how to target the last n number of elements here.

In CSS, :nth-child refers to the child referenced from the beginning of the parent. Take an example:

<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>

If you were to select :nth-child(2), then the second <li> is selected. So this:

ul:nth-child(2) {
color: red;
}

Would make two red.

Moving in the other direction is :nth-last-child, which moves backwards. So, this:

ul:nth-last-child(2) {
color: red;
}

Would make three red.

Now, let's say we wanted to make the last two elements red. We can use -n and move backwards from the end. So:

ul:nth-last-child(-n + 2) {
color: red;
}

Affects both three and four.

The iterator follows the pattern of an+b. If you want to learn more about how this iteration logic works, Chris Coyier has a great explanation.

Let's Connect

Keep Reading

A Simple CSS Build Pipeline Using PostCSS

PostCSS is a super powerful tool that can help you craft your own CSS build pipeline. But it can be a lot to take in all at once. Here are a few quick steps to getting started with PostCSS.

Jun 03, 2021

Add Custom JavaScript and Stylesheets from SharePoint Master Page

You can add JavaScript and CSS files to your master page if you want to overwrite some default styles or add some functionality via a new script.

Aug 06, 2013

3 CSS Button Generators To Help You Style Buttons

A few references for styling buttons with CSS. I'll also point you to a couple CSS frameworks.

Feb 06, 2013