Khi viết CSS, đôi khi muốn target một phần tử cụ thể. Giả sử có document HTML đầy thẻ <div> và <span>, nhưng chỉ muốn style cho thẻ đầu tiên của mỗi loại. Chúng ta làm được điều đó với pseudo-class :first-of-type.
Pseudo-class là cách để CSS selector có style cụ thể khác với style gốc, tùy thuộc vào trạng thái của phần tử. Ở đây, muốn chọn <div> đầu tiên và <span> đầu tiên để style – không span hay div nào khác bị chọn.
Ví dụ khởi đầu:
<html>
<head>
<style>
body { display: flex; flex-flow: row wrap; }
div { height: 100px; width: 200px; border: 1px solid black; margin: 20px; padding: 20px; }
/* First of type */
div:first-of-type { background: purple; color: white; }
div span:first-of-type { color: red; text-decoration: underline; background: lightblue; }
</style>
</head>
<body>
<div>I am the first div<span> I am inside the div and the first span</span><span> I am the second span</span></div>
<div>I am the second the div<span> I am inside the div</span><span> I am the second span</span></div>
<div>I am the third div<span> I am inside the div</span><span> I am the second span</span></div>
<div>I am the fourth div<span> I am inside the div</span><span> I am the second span</span></div>
<div>I am the fifth div<span> I am inside the div</span><span> I am the second span</span></div>
<div>I am the sixth div<span> I am inside the div</span><span> I am the second span</span></div>
<div>I am the seventh div<span> I am inside the div</span><span> I am the second span</span></div>
</body>
</html>
Ở đây có tập hợp div và span bên trong div. Selector div:first-of-type chỉ chọn phần tử đầu tiên của loại đó và style nó. Selector div span:first-of-type chọn span đầu tiên trong mỗi div vì div là phần tử cha.
div:first-of-type tương đương với div:nth-child(1).
Kết Luận
Bài này tìm hiểu pseudo-class :first-of-type. Pseudo-class cơ bản chỉ mô tả trạng thái mong muốn của CSS selector khi styling. Cũng xem xét cú pháp chung. Đề xuất tìm hiểu thêm các pseudo-selector khác để nắm rõ hơn!