CSS :first-child pseudo-class chọn một phần tử là phần tử con đầu tiên của một phần tử cha khác.
Cú pháp
:first-child {
/*declarations*/
}
Ví dụ 1: Bỏ border-left cho first child trong table
<!DOCTYPE html>
<html>
<head>
<style>
table { margin: auto; padding: 10px; border: hsl(54, 100%, 50%) solid 13px; border-radius: 6px; text-align: center; }
td, th { border-left: 2px solid black; border-top: 3px solid black; }
td:first-child, th:first-child { border-left: none; }
th { background-color: lightblue; border-top: none; }
caption { margin-top: 3px; background-color: purple; caption-side: bottom; color: white; border-radius: 20%; }
</style>
</head>
<body>
<table>
<caption>MCA Syllabus</caption>
<tr> <th colspan="4">Subjects</th> </tr>
<tr> <td>C</td> <td>C++</td> <td>Java</td> <td>C#</td> </tr>
<tr> <td>MySQL</td> <td>PostgreSQL</td> <td>MongoDB</td> <td>SQLite</td> </tr>
</table>
</body>
</html>
Kết quả
Trước khi dùng first-child pseudo-class selector:

Sau khi dùng first-child pseudo-class selector:

Ví dụ 2: :first-child trên list items
<!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>
<h2>Apache Spark</h2>
<ul>
<li>Apache Spark is a lightning-fast cluster computing technology, designed for fast computation. </li>
<li>It is based on Hadoop MapReduce.</li>
Kết quả

Lưu ý quan trọng:
:first-childchọn phần tử là con đầu tiên của phần tử cha, bất kể loại thẻ- Khác với
:first-of-type- chọn phần tử đầu tiên của loại đó trong cha - Ví dụ:
p:first-childchỉ khớp nếu<p>là con đầu tiên của cha. Nếu con đầu tiên là<h1>thì không khớp.
So sánh:
| Selector | Chọn gì? | Ví dụ khớp |
|---|---|---|
:first-child | Con đầu tiên của parent (bất kỳ loại) | Div đầu tiên trong container |
:first-of-type | Con đầu tiên CỦA LOẠI ĐÓ của parent | P đầu tiên trong container (dù h1 ở trước) |
:nth-child(1) | Tương đương :first-child | Cùng ý nghĩa |
:nth-of-type(1) | Tương đương :first-of-type | Cùng ý nghĩa |
Ứng dụng thực tế: Bỏ border đầu/cuối, styling đặc biệt cho item đầu tiên trong list/menu/card grid, typography (drop cap).