CSS nth-child Tester

GigaBook Web Developer Tools

Odd Or Even

For example the most common task for selecting items in a collection of items is to get even or odd items. In the past we would have to use CSS classes in the HTML and make sure we add an odd or even.


<ul>
    <li class="odd"></li>
    <li class="even"></li>
    <li class="odd"></li>
    <li class="even"></li>
    <li class="odd"></li>
    <li class="even"></li>
</ul>

Using these different CSS classes we can now style these list items differently.


.odd
{
    background: #a1a1a1;
}
.even
{
    background: #eeeeee;
}

But using the nth-child selector we can do this without the need for extra CSS classes.

The nth-child selector allows us to pass through a parameter of the items we need to collect, so to style the odd and even items with the nth-child selector we can simply use the following code.


<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

Then style these items by using this CSS.


li:nth-child(odd)
{
    background: #a1a1a1;
}
li:nth-child(even)
{
    background: #eeeeee;
}

Select Specific Item

If you want to select a specific item you can do this by entering the number of the item you want to select. If you want to select the 4th item in the list then all you have to do is pass in the number 4 into the nth-child() selector.


li:nth-child(4)
{
    background: #a1a1a1;
}

Select Every 3rd Item

Using the nth-child selector you can also select a pattern of items, for example if you want to select every 3rd item then you can do so by passing in 3n+1, this means that we will start at item 1 and then select every 3rd item.


li:nth-child(3n+1)
{
    background: #a1a1a1;
}

If you want the pattern to start at item 2 then you will use the value 3n+2.


li:nth-child(3n+2)
{
    background: #a1a1a1;
}

Nth-child Tester

If you are interested in learning more about how the nth-child selector works we have built an nth-child tester tool, which allows you to select from a list of common values used for nth-child. As soon as you select a new value the tool will highlight which items this will select. You can even change this value to anything you want to see how new patterns will select the different items.

Sign up now for your free trial

Join Coveloping membership from $4.99 a month and get your first month free, cancel at any time


Start Now

Need help with your website? Hire a coveloping freelancer - fill out our quick form with your requirements and we'll get back to you with an estimate and availabilty. Find out more...

Code Copied!