Pitch your project

Random text






Blogs

0    
By admin Category Uncategorized, Posted February 10th, 2016
nth-child selectors

nth-child() selectors can be quite handy when you want to select a specific range of elements for styling. They will allow you to select multiple elements in 1 line. In this blog I’ll go over the basics of the nth-child() selector.

Using nth-child

With the nth-child(number) selector you can specifically select 1 element from a row of elements.

li:nth-child(3){
    background: green;
}

Child ranges

You can select a specific row of elements by using child ranges. By putting n in front of the number, you will select the number and all the elements above it. You can also do the opposite by using -n, this will select the number and all the elements in behind it.

li:nth-child(n+3){
    background: green;
}

li:nth-child(-n+5){
    background: yellow;
}

These two pieces of code will have the respective results.

If you want to get a middle row of elements you can combine both of the previous selectors like this:

    li:nth-child(n+3):nth-child(-n+6){
        background: green;
    }

Odd and Even

The nth-child() selectors also accept odd and even as value. They will only select the odd or even elements.

    li:nth-child(odd){
        background: green;
    }

    li:nth-child(even){
        background: yellow;
    }

Chained Selectors

All of the selectors can be chained together to get the most out of them. Here is an example:

    li:nth-child(even):nth-child(-n+6){
        background: yellow;
        border-radius: 30px;
    }

    li:nth-child(even):nth-child(n+4):nth-child(-n+6){
        background: green;
        border-radius: 30px;
    }

    li:nth-child(odd){
        background: red;
    }

I’ll give a small explanation of whats happening.
The first function gets the even elements which are 6 or lower (2, 4, 6) and makes them round and yellow.
The second function gets the even elements which are in between 3 and 7 (4, 6) and makes them round and green.
The final function gets all the uneven elements (1, 3, 5, 7, 9) and colours them red.

nth-childs can make styling a group of elements a lot easier then styling them all separately. These are just simple examples of what you can do with them, but they are very powerful if used wisely.

Posted by Nick Duijndam

Leave a Reply

Your email address will not be published. Required fields are marked *