2022 IT 鐵人賽 [ Day 6] [ CSS ] — Pseudo-classes 偽類 (2)

Daisy
5 min readSep 20, 2022

--

大家好,接續昨天的介紹…

Structural pseudo-classes

這些偽類與 document tree 的位置有關。index 是從 1 開始。

- :root
根目錄,在 HTML 中等同於 <html> 元素 ,優先權比 <html> 元素還要高。
常用在 CSS variables
- :empty
空值,選取沒有任何子元素的父元素

— — 只管順序,不管類型 — —

- :nth-child(an+b)
同級元素當中的第幾個

(an+b):
n 是從 0 開始的數列:0 1 2 3 4 5 … n,可以是
- 單一數字:(3)
- 關鍵字:(odd)奇數、(even)偶數
- 公式:(3n),表示選取到 3 6 9 12 等 3 的倍數;(2n+1),表示選取到 1 3 5 等奇數

- :nth-last-child(an+b)
同上,但是從倒數開始
- :first-child
同級元素中的第一個,等同於 :nth-child(1)
- :last-child
同級元素中的最後一個,等同於 :nth-last-child(1)
- :only-child
沒有其他同級元素(兄弟元素),該層只有自己,等同於 :first-child:last-child、:nth-child(1):nth-last-child(1)

— — 先做分類(tag name),再做順序 — —

- :nth-of-type(an+b)
同類型當中的第幾個
- :nth-last-of-type(an+b)
同上,但是從倒數開始
- :first-of-type
同級元素中且同類型的第一個,等同於 :nth-of-type(1)
- :last-of-type
同級元素中且同類型的最後一個,等同於 :nth-last-of-type(1)
- :only-of-type
沒有其他同類型的同級元素(兄弟元素),該層只有自己,等同於 :first-of-type:last-of-type、:nth-of-type(1):nth-last-of-type(1)

The negation pseudo-class

- :not(selector)
否定,選取所有的元素但是排除掉指定元素

Example

// HTML
<div>
<p>paragraph 1</p>
</div>
<div>
<p>paragraph 2</p>
<p>paragraph 2–2</p>
</div>
<div>
<p>paragraph 3</p>
<p>paragraph 3–2</p>
<p>paragraph 3–3</p>
</div>
<div>
<p>paragraph 4</p>
<p>paragraph 4–2</p>
<p>paragraph 4–3</p>
<p>paragraph 4–4</p>
</div>
<div></div><ul>
<li>This is item 1.</li>
<li>This is item 2.</li>
<li>This is item 3.</li>
<li>This is item 4.</li>
<li>This is item 5.</li>
<li>This is item 6.</li>
<li>This is item 7.</li>
<li>This is item 8.</li>
<li>This is item 9.</li>
<li>This is item 10.</li>
</ul>
// CSS
/* 第五個 li */
li:nth-child(5) {
color: blue;
}
/* ul 中 3 的倍數的子元素,3、6、9 */
ul :nth-child(3n) {
color: green;
}
/* 與上面一樣 */
li:nth-child(3n) {
text-decoration: underline;
}
/* 倒數第四個 li,item 7*/
li:nth-last-child(4) {
color: red;
}
/* body 裡的第一個名為 div 的子元素 */
div:first-child {
color: pink;
}
/* div 裡的第一個子元素,paragraph 1、paragraph 2、paragraph 3、paragraph 4 */
div :first-child {
text-decoration: line-through;
}
/* div 裡的最後一個子元素,paragraph 1、paragraph 2–2、paragraph 3–3、paragraph 4–4 */
div :last-child {
border: 1px solid gray;
}
/* div 裡的只有一個子元素 */
div :only-child {
background-color: yellow;
}
/* div 中的第四個、li 中的第四個 */
:nth-of-type(4) {
color: purple;
}
/* div 裡沒有子元素 */
div:empty {
height: 20px;
background-color: orange;
}
/* div 中的 p 設為斜體,除了最後一個 */
div p:not(:last-child) {
font-style: italic;
}

Codepen

參考資料:
W3C — #Structural pseudo-classes
MDN — #tree-structural_pseudo-classes
W3schools — Pseudo-classes

文章同步更新於 2022 IT鐵人賽

--

--