{"id":14234,"date":"2011-09-06T20:21:11","date_gmt":"2011-09-07T03:21:11","guid":{"rendered":"http:\/\/css-tricks.com\/?page_id=14234"},"modified":"2021-11-05T13:00:02","modified_gmt":"2021-11-05T20:00:02","slug":"nth-of-type","status":"publish","type":"page","link":"https:\/\/css-tricks.com\/almanac\/selectors\/n\/nth-of-type\/","title":{"rendered":":nth-of-type"},"content":{"rendered":"\n

The :nth-of-type<\/code> selector allows you select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec<\/a> as a \u201cstructural pseudo-class\u201d, meaning it is used to style content based on its relationship with parent and sibling elements.<\/p>\n\n\n\n

Suppose we have an unordered list and wish to \u201czebra-stripe\u201d alternating list items:<\/p>\n\n\n\n

<ul>\n  <li>First Item<\/li>\n  <li>Second Item<\/li>\n  <li>Third Item<\/li>\n  <li>Fourth Item<\/li>\n  <li>Fifth Item<\/li>\n<\/ul><\/code><\/pre>\n\n\n\n

Rather than adding classes to each list item (eg .even<\/code> & .odd<\/code>) we can use :nth-of-type<\/code>:<\/p>\n\n\n\n

li {\n  background: slategrey;\n}\n\/* select alternating items starting with the second item *\/\nli:nth-of-type(2n) {\n  background: lightslategrey;\n}<\/code><\/pre>\n\n\n\n

<\/code>As you can see, :nth-of-type<\/code> takes an argument: this can be a single integer, the keywords \u201ceven\u201d or \u201codd\u201d, or a formula as shown above. If an integer is specified only one element is selected\u2014but the keywords or a formula will iterate through all the children of the parent element and select matching elements\u2014similar to navigating items in an array in JavaScript. Keywords \u201ceven\u201d and \u201codd\u201d are straightforward, but the formula is constructed using the syntax an+b<\/code>, where:<\/p>\n\n\n\n

  • \u201ca\u201d is an integer value<\/li>
  • \u201cn\u201d is the literal letter \u201cn\u201d<\/li>
  • \u201c+\u201d is an operator and may be either \u201c+\u201d or \u201c-\u201d<\/li>
  • \u201cb\u201d is an integer and is required if an operator is included in the formula<\/li><\/ul>\n\n\n\n

    It is important to note that this formula is an equation, and iterates through each sibling element, determining which will be selected. The \u201cn\u201d part of the formula, if included, represents a set of increasing positive integers (just like iterating through an array). In our above example, we selected every second element with the formula 2n<\/code>, which worked because every time an element was checked, \u201cn\u201d increased by one (2\u00d70, 2\u00d71, 2\u00d72, 2\u00d73, etc). If an element’s order matches the result of the equation, it gets selected (2, 4, 6, etc). For a more in-depth explanation of the math involved, please read this article<\/a>.<\/p>\n\n\n\n

    To illustrate further, here are some examples of valid :nth-of-type<\/code> selectors:<\/p>\n\n\n\n