Pseudo-class :nth-child() trong CSS chọn một phần tử là phần tử con thứ n của một phần tử khác.
Cú pháp
:nth-child(/* pattern */) {
/* declarations */
}
Các pattern phổ biến
| Pattern | Ý nghĩa |
|---|---|
:nth-child(3) | Phần tử con thứ 3 |
:nth-child(2n) / :nth-child(even) | Các phần tử con chẵn (2, 4, 6...) |
:nth-child(2n+1) / :nth-child(odd) | Các phần tử con lẻ (1, 3, 5...) |
:nth-child(3n) | Mỗi phần tử thứ 3 (3, 6, 9...) |
:nth-child(-n+3) | Ba phần tử đầu tiên |
:nth-child(n+4) | Từ phần tử thứ 4 trở đi |
:nth-child(n+2):nth-child(-n+4) | Phần tử 2, 3, 4 |
Ví dụ 1: Màu cho từng div con
<!DOCTYPE html>
<html>
<head>
<title>CSS :nth-child() Pseudo Class</title>
<style>
form { width: 70%; margin: 0 auto; text-align: center; }
* { padding: 2px; margin: 5px; box-sizing: border-box; }
input[type="button"] { border-radius: 10px; }
.child {
display: inline-block;
height: 40px; width: 40px;
color: white; border: 4px solid black;
}
.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; }
.child:nth-child(6) { background-color: #FEDC11; }
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS :nth-child() Pseudo Class</legend>
<div id="container">
<div class="child"></div><div class="child"></div><div class="child"></div>
<div class="child"></div><div class="child"></div><div class="child"></div>
</div><br>
</fieldset>
</form>
</body>
</html>
Ví dụ 2: Style cho các li cụ thể
<!DOCTYPE html>
<html>
<head>
<style>
* { font-size: 1.1em; list-style: circle; }
li:first-child { background-color: seashell; font-family: cursive; }
li:nth-child(2) { background-color: azure; font-family: "Brush Script Std", serif; }
li:last-child { background-color: springgreen; font-family: "Gigi", Arial; }
</style>
</head>
<body>
<p>Famous Cricket Stadiums</p>
<ul>
<li>Eden Gardens, Kolkata, India</li>
<li>Melbourne Cricket Ground, Melbourne, Australia</li>
<li>DY Patil Sports Stadium, Navi Mumbai, India</li>
</ul>
</body>
</html>
Lưu ý quan trọng
:nth-childđếm tất cả các phần tử con, không chỉ những phần tử khớp selector- Nếu muốn chỉ đếm các phần tử cùng loại, dùng
:nth-of-type() - Index bắt đầu từ 1, không phải 0
Ví dụ nth-child vs nth-of-type
<div>
<p>P1</p> <!-- nth-child(1), nth-of-type(1) -->
<span>S1</span> <!-- nth-child(2) -->
<p>P2</p> <!-- nth-child(3), nth-of-type(2) -->
<span>S2</span> <!-- nth-child(4) -->
</div>
p:nth-child(2) { color: red; } /* Không khớp gì (S1 là span) */
p:nth-of-type(2) { color: red; } /* Khớp P2 */