My Favorite Child Is The Nth One

You’re going to love this post like your mother never did.

Does the nth child notation confuse you much like the actions of your least favorite child? Well, this simple tutorial will make you a master. Best of all, these CSS selectors work as jQuery selectors too, so you can grab any nth element of any kind with the greatest of ease. Don’t worry if your actual children get jealous, just send them to their room, fire up the ole’ Mac Book and get a coffee. It’s time for some natural selection.

 

Select Only the 5th element

li:nth-child(5) {
    color: orange;
}
Select All but the First Five

li:nth-child(n+6) {
    color: orange;   
}
Select Only the First Five

li:nth-child(-n+5) {
    color: orange;   
}
Select Every Fourth Starting from the First

li:nth-child(4n+1) {  /* or 4n-7 */
    color: orange;   
}
Putting It All Together

And now to get really fancy. I use this technique often to display columns in a responsive pattern. By changing the nth child dependent on a media query you can display a different number of columns depending on the width of the page.

HTML

<div class="element">Element 1</div>
<div class="element">Element 1</div>
<div class="element">Element 1</div>
<div class="element">Element 1</div>

CSS

.element {
    float: left;
    width: 25%;
}

@media (max-width: 600px) {
    .element {
        width: 50%;
    }
    .element(odd) {
        clear: left;
    }
}

12
Mar
2017

Leave a Reply

Your email address will not be published.
*