CSS 偽類選擇器 (Pseudo-classes)

偽類 (pseudo-class) 用來選取處於特定狀態的元素,例如滑鼠移到上面、被點擊、第一個子元素等。偽類的語法是在選擇器後面加上冒號 : 和偽類名稱。

selector:pseudo-class {
  property: value;
}

連結相關偽類

/* 尚未被訪問過的連結 */
a:link {
  color: blue;
}

/* 已經訪問過的連結 */
a:visited {
  color: purple;
}

:hover

當滑鼠移到元素上面時套用的樣式。

a:hover {
  color: red;
  text-decoration: underline;
}

button:hover {
  background-color: darkblue;
}

:active

當元素被點擊的瞬間(滑鼠按下還沒放開)套用的樣式。

button:active {
  transform: scale(0.98);
}
連結偽類的順序很重要,建議按照 :link → :visited → :hover → :active 的順序撰寫,可以用「LoVe HAte」來記憶。

表單相關偽類

:focus

當元素獲得焦點時(例如點擊輸入框)。

input:focus {
  border-color: blue;
  outline: none;
}

:disabled 和 :enabled

input:disabled {
  background-color: #eee;
  cursor: not-allowed;
}

input:enabled {
  background-color: white;
}

:checked

用於被勾選的 checkbox 或 radio button。

input:checked {
  accent-color: green;
}

/* 搭配相鄰選擇器,改變勾選後的標籤樣式 */
input:checked + label {
  font-weight: bold;
}

:required 和 :optional

input:required {
  border-left: 3px solid red;
}

input:optional {
  border-left: 3px solid gray;
}

:valid 和 :invalid

根據表單驗證結果套用樣式。

input:valid {
  border-color: green;
}

input:invalid {
  border-color: red;
}

結構偽類

:first-child 和 :last-child

/* 選取父元素中的第一個子元素 */
li:first-child {
  font-weight: bold;
}

/* 選取父元素中的最後一個子元素 */
li:last-child {
  border-bottom: none;
}

:nth-child(n)

選取父元素中的第 n 個子元素。

/* 選取第 3 個 li */
li:nth-child(3) {
  color: red;
}

/* 選取偶數個 li */
li:nth-child(even) {
  background-color: #f5f5f5;
}

/* 選取奇數個 li */
li:nth-child(odd) {
  background-color: white;
}

/* 每隔 3 個選取 */
li:nth-child(3n) {
  color: blue;
}

/* 從第 3 個開始選取 */
li:nth-child(n+3) {
  opacity: 0.5;
}

:nth-last-child(n)

從最後面開始數的第 n 個子元素。

/* 選取倒數第 2 個 */
li:nth-last-child(2) {
  color: orange;
}

:only-child

選取是父元素唯一子元素的元素。

p:only-child {
  font-size: 20px;
}

:first-of-type 和 :last-of-type

選取同類型元素中的第一個或最後一個。

/* 選取第一個 p 元素 */
p:first-of-type {
  font-size: 1.2em;
}

:nth-of-type(n)

/* 選取第偶數個 p 元素 */
p:nth-of-type(even) {
  background-color: #f0f0f0;
}

其他偽類

:not()

選取「不符合」指定選擇器的元素。

/* 選取所有不是 .special 的 p */
p:not(.special) {
  color: gray;
}

/* 選取所有不是第一個的 li */
li:not(:first-child) {
  border-top: 1px solid #ddd;
}

:empty

選取沒有任何子元素(包括文字)的元素。

div:empty {
  display: none;
}

:target

選取當前 URL 錨點 (#) 指向的元素。

/* 當 URL 是 page.html#section1 時,#section1 會被選取 */
:target {
  background-color: yellow;
}

常用偽類總覽

偽類說明
:hover滑鼠移上去
:active被點擊中
:focus獲得焦點
:first-child第一個子元素
:last-child最後一個子元素
:nth-child(n)第 n 個子元素
:not(selector)不符合選擇器的元素
:checked被勾選的表單元素
:disabled被禁用的表單元素