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
Selected Reading
The :nth-child Pseudo-class in CSS
The CSS :nth-child() pseudo-class selects an element that is the nth child of its parent. It allows you to target specific child elements based on their position in the parent container.
Syntax
:nth-child(n) {
/* declarations */
}
Possible Values
| Value | Description |
|---|---|
number |
Selects the nth child element (1, 2, 3, etc.) |
odd |
Selects all odd-positioned child elements |
even |
Selects all even-positioned child elements |
2n+1 |
Formula-based selection (every 2nd element starting from 1st) |
Example 1: Styling Multiple Child Elements
The following example demonstrates how to style different child elements using :nth-child() −
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: flex;
gap: 10px;
margin: 20px;
}
.child {
width: 50px;
height: 50px;
border: 2px solid #000;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
color: white;
}
.child:nth-child(1) {
background-color: #FF8A00;
}
.child:nth-child(2) {
background-color: #F44336;
}
.child:nth-child(3) {
background-color: #C303C3;
}
.child:nth-child(4) {
background-color: #4CAF50;
}
.child:nth-child(5) {
background-color: #03A9F4;
}
</style>
</head>
<body>
<div class="container">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
<div class="child">5</div>
</div>
</body>
</html>
Five colored squares appear in a row, each with a different background color: orange (1), red (2), purple (3), green (4), and blue (5).
Example 2: Styling List Items
This example shows how to use :nth-child() with list items −
<!DOCTYPE html>
<html>
<head>
<style>
ul {
max-width: 400px;
margin: 20px;
padding: 0;
list-style: none;
}
li {
padding: 10px;
margin: 5px 0;
border-radius: 5px;
}
li:nth-child(odd) {
background-color: #f0f0f0;
}
li:nth-child(even) {
background-color: #e0e0e0;
}
li:nth-child(2) {
background-color: #2196F3;
color: white;
font-weight: bold;
}
</style>
</head>
<body>
<h3>Famous Cricket Stadiums</h3>
<ul>
<li>Eden Gardens, Kolkata, India</li>
<li>Melbourne Cricket Ground, Melbourne, Australia</li>
<li>DY Patil Sports Stadium, Navi Mumbai, India</li>
<li>Lord's Cricket Ground, London, England</li>
</ul>
</body>
</html>
A list of cricket stadiums appears with alternating light gray backgrounds for odd items and darker gray for even items. The second item (Melbourne Cricket Ground) is highlighted in blue with white text.
Conclusion
The :nth-child() pseudo-class is a powerful tool for selecting and styling specific child elements. Use numeric values for precise targeting or keywords like odd and even for pattern-based styling.
Advertisements
