了解 CSS3 中 :nth-of-type() 偽類選擇器的使用
功能描述
:nth-of-type 是 CSS3 的一個偽類選擇器,它可以根據元素在其同類型兄弟元素中的位置來選擇一個或多個元素,而無需添加額外的類或 ID。這個偽類的參數可以是一個數字、關鍵詞(如 odd 或 even),或者是一個公式(如 an+b)。
代碼示例
示例的 html 文件:
<!DOCTYPE html>
<html>
<head>
<style>
/* 設置樣式 */
</style>
</head>
<body>
<p>第一個段落。</p>
<p>第二個段落。</p>
<p>第三個段落。</p>
<p>第四個段落。</p>
<p>第五個段落。</p>
</body>
</html>
1.選擇第二個 <p> 元素時:
p:nth-of-type(2) {
/* 設置樣式 */
background-color: green;
}

2.選擇所有奇數位置的 <p> 元素時,使用關鍵詞 odd:
p:nth-of-type(odd) {
/* 設置樣式 */
background-color: green;
}

3.選擇每個循環(循環周期為 a)中第 b 個元素時,則使用公式 an+b:
/* 選擇位置為 3 的倍數的所有 <p> 元素 */
p:nth-of-type(3n+0) {
/* 設置樣式 */
background-color: green;
}

/* 選擇位置為 2、5、8、……、3n+2 的所有 <p> 元素 */
p:nth-of-type(3n+2) {
/* 設置樣式 */
background-color: green;
}

參考文檔
:nth-of-type() - CSS: Cascading Style Sheets | MDN
CSS :nth-of-type() Pseudo-class - w3schools
CSS3 :nth-of-type() 選擇器 - w3school 在線教程


浙公網安備 33010602011771號