What is nth-of-type in CSS?
Let us consider a task that we want to achieve to understand what this nth-of-type in CSS is. Say, for example, we want to color every alternate element in a list blue, as show in the figure below.
Now, to do this task, one thing we can do is add two classes “odd” and “even” and put blue color to the odd classes. But, there can be a situation where we want to color 3 elements consecutively in the order of red, green, and blue. Then making three different classes to solve the problem isn’t something we would call smart coding, right? This issue can be solved with nth-of-type in CSS.
Definition
The :nth-of-type is a selector that allows us to use a formula (or, expression) to select one or more items based on their source order. This is defined as a "structural pseudo-class" in the CSS Selectors Level 3 specification. In other words, they are used to style only elements that are the nth child of the parent element.This n can be a number, keyword, or expression.
Syntax
Type 1:
Type 2:
:::section {.tip} Note: keyword mainly used are “even” and “odd”. :::
Type 3:
Examples
Now, let us take a few examples to get a deeper understanding on how nth-of-type selector works.
Example 1
Let us consider an example where we are coloring the odd and even paragraph elements with two different background colors.
HTML:
CSS:
Here we have used the type 2 syntax :nth-of-type(keyword). All the even p elements have one background color, while the odd ones have another one!
Output:
Example 2
Let us take another example where we will be specifying a background color of the p element whose index is a multiple of 3.
HTML:
CSS:
Here we have used the type 3 syntax :nth-of-type(expression/formula). The background color of the p element whose index is a multiple of 3 have been changed.
Output:
Browser Compatibility
Now, let us go through the browser compatibility. The numbers in the table indicate the first browser version that fully supported this selectors.
Browser Name | First browser version supporting |
---|---|
Google Chrome | 4.0 |
Microsoft Edge (Chromium) | 9.0 |
Morzilla Firefox | 3.5 |
Safari - Apple | 3.2 |
Opera | 9.6 |
Conclusion
So, in this article we have studied about the :nth-of-type selector. At, a glance let’s see what we have seen till now.
- :nth-of-type() is used to style only elements that are the nth child of the parent element.
- The nth child of the parent can be selected based on:
- Numeric value
- Keyword
- Expression
- Numeric value