:nth-of-type(n) by Brad Koehler

As our web builds have moved more toward HTML5 and CSS3, I have noticed some selectors cropping up more and more in my work. One of the ones I find myself using most often is :nth-of-type.

What is it?

:nth-of-type() is a CSS3 pseudo class selector.

What does it do?

The :nth-of-type() selector allows you to target elements based on their position in the document tree.

For example:


<article class="topStory">
<section>First section</section>
<section>First section</section>
<section>First section</section>


article.topStory section:nth-of-type(2) {

This code will apply the styles to the second section element.

This has the added effect of simplifying your HTML markup, reducing the need for classes or ID's and making dynamic code chunks more straight forward.

Example use case

Imagine you have to build an image or product gallery, you have a container of 600px width and you have rows of 3 elements that are 190px wide with a 15px gutter between them.

Graphic representing a layout of 600px with a grid of elements 190px wide

You might choose to mark this up as an unordered list. With each <li> having a right margin of 15px and then a class on every third element to overwrite that margin with 0.


<ul><li>Element 190px</li>
<li>Element 190px</li>
<li class="noRightMargin">Element 190px</li>


ul li {width:190px; float:left; margin:0 15px 15px 0;}
ul li.noRightMargin {margin-right:0;}

Now this works, however you now have an ugly class name in your HTML and you have to find a way to dynamically add that class to every third element. PITA

However :nth-of-type() can provide us with a tidier way to achieve this same result.

With nth-of-type() you can specify a value of n, such as;

ul li:nth-of-type(3n) {

This will select every third element in the list and eliminates the need to have a class on the item, therefore saving us the headache of dynamically generating that class

Other applications

There are several other options available for use with :nth-of-type(). To select every fourth item in a list for example, you could use

ul li:nth-of-type(5n-1){}


ul li:nth-of-type(3n+1){}

you can also use the options "odd" and "even". I can imagine that this would be particularly useful when Zebra striping table rows.


As always there is good support for :nth-of-type() in the more modern browsers and as always there is not any support for it in IE8 and back.

Fear Not!

There is a brilliantly useful JavaScript library called Selectivzr that adds support for lots of CSS3 pseudo selectors to older versions of IE. You can check it out at selectivizr.com

Posted on 15 May 2012, 11:05 a.m. by Brad Koehler