As Front End Web Devs CSS is our biggest tool. CSS itself keeps getting better and better. We need to keep up on our tool to use it to its fullest. I’d like to talk about a pseudo-selector tool that I have not used much that I would like to embrace in upcoming projects. I find that it will be really valuable to me. I think the Backend Devs will like it to because I won’t have to come bug them as much if I can make proper use of this selector. It is the nth-child selector.

Lets say that a client decided they would like the background of every other <li> tag to be darker than the rest. This <li> is created dynamically. In the past I would have to go contact a Back End Dev and have him write some code to put a class on every other <li>. Then I would go style those with the new class. With the use of the nth-child pseudo selector I can do this with the CSS alone. Here’s how:
ul li:nth-child(2n+1) { background:#212121; }
The expression 2n+1 will match the first, third, fifth, seventh, and so on, elements if they exist. 2n+1 isn’t the only expression you can run. Here is a list of a few possibilities:
- 4n+1 would select the first, fifth, ninth, thirteenth…
- 4n would select fourth, eighth, twelfth, sixteenth…
- -n+5 would select fifth, fourth, third, second, first, none
If this isn’t making perfect sense yet just run the math loop in your head and it will. Lets take the first example again. 2n+1
- 2*0+1=1
- 2*1+1=3
- 2*2+1=5
- 2*3+1=7
Before we go out and use this everywhere I should point out that IE doesn’t support this in any of its versions. The saving point to this though is that jQuery does support all CSS selectors so if you are using jQuery you should be fine. For examples of how the nth-child works with jQuery see this page. Happy Coding.








