Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Role of CSS :nth-of-type(n) Selector
The CSS :nth-of-type(n) selector is used to select and style elements that are the nth child of their specific type within their parent element. This pseudo-class is particularly useful when you want to target specific elements based on their position among siblings of the same tag type.
Syntax
element:nth-of-type(n) {
property: value;
}
Possible Values
| Value | Description |
|---|---|
number |
Selects the element at the specified position (1, 2, 3, etc.) |
odd |
Selects all odd-positioned elements of the same type |
even |
Selects all even-positioned elements of the same type |
an+b |
Selects elements using a formula (e.g., 2n+1, 3n+2) |
Example: Selecting Specific Position
The following example selects the second paragraph element and applies a yellow background −
<!DOCTYPE html>
<html>
<head>
<style>
p:nth-of-type(2) {
background-color: yellow;
padding: 10px;
margin: 5px 0;
}
p {
border: 1px solid #ccc;
padding: 10px;
margin: 5px 0;
}
</style>
</head>
<body>
<p>This is demo text 1.</p>
<p>This is demo text 2.</p>
<p>This is demo text 3.</p>
<p>This is demo text 4.</p>
</body>
</html>
Four paragraphs appear on the page with borders. The second paragraph has a yellow background, while the others remain white.
Example: Using Odd and Even Keywords
This example demonstrates styling odd and even positioned elements differently −
<!DOCTYPE html>
<html>
<head>
<style>
li:nth-of-type(odd) {
background-color: #f0f0f0;
color: #333;
}
li:nth-of-type(even) {
background-color: #333;
color: white;
}
li {
padding: 8px;
margin: 2px 0;
list-style-type: none;
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
</body>
</html>
A list appears with alternating styles: odd items (1, 3, 5) have light gray backgrounds with dark text, while even items (2, 4) have dark backgrounds with white text.
Conclusion
The :nth-of-type(n) selector provides precise control over styling elements based on their position among siblings of the same type. It's especially useful for creating alternating patterns and targeting specific elements without adding extra classes.
