Trong CSS, :nth-last-of-type() Selector được dùng để tạo kiểu cho phần tử con thứ n của phần tử cha. Bộ chọn đếm từ phần tử last-child
. n có thể là số, từ khóa hoặc công thức.
Cú pháp:
:nth-last-of-type(number) {
//css Property;
}
Trong đó number là tham số đại diện cho mẫu để so khớp các phần tử từ cuối lên. Nó có thể là odd, even hoặc một ký hiệu hàm.
- odd: Đại diện cho các phần tử có vị trí lẻ trong một chuỗi: 1, 3, 5... đếm từ cuối.
- even: Đại diện cho các phần tử có vị trí chẵn trong một chuỗi: 2, 4, 6... đếm từ cuối.
- functional notation (): Đại diện cho các phần tử có vị trí anh chị em khớp với mẫu An+B. Với mọi số nguyên dương hoặc giá trị 0 của n. Chỉ số của phần tử đầu tiên đếm từ cuối là 1.
Ví dụ 1:
html<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: green;
font-size: 35px;
}
p:nth-last-of-type(3) {
background: green;
color: white;
font-weight: bold;
width: 70%;
}
</style>
</head>
<body>
<center>
<h1>GeeksForGeeks</h1>
<h2>CSS:nth-last-of-type() Selector </h2>
<p class="geeksFORGEEKS">geeksforgeeks</p>
<p class="forgeeks">A computer science portal for geeks.</p>
<p class="geeks">Sudo placement.</p>
<p class="SUDO">GFG STANDS FOR GEEKSFORGEEKS.</p>
</center>
</body>
</html>
Đầu ra:
Ví dụ 2: Trong ví dụ này, mọi phần tử chẵn được chọn theo công thức 2n tính từ cuối.
html<!DOCTYPE html>
<html>
<head>
<title>CSS :nth-last-of-type Selector</title>
<style>
table {
border: 1px solid green;
margin: auto;
}
/* Selects the last three element */
tr:nth-last-of-type(2n) {
background-color: green;
color: white;
}
</style>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h2>
CSS :nth-last-of-type Selector
</h2>
<table>
<tbody>
<tr>
<td>Merge sort</td>
</tr>
<tr>
<td>Quick sort</td>
</tr>
<tr>
<td>Insertion sort</td>
</tr>
<tr>
<td>Selection sort</td>
</tr>
</tbody>
</table>
</body>
</html>
Đầu ra:
Các trình duyệt được hỗ trợ: Các trình duyệt hỗ trợ :nth-last-of-type() Selector được liệt kê dưới đây:
- Apple Safari 3.1
- Google Chrome 4
- Edge 12
- Firefox 3.5
- Opera 9.5