CSS - 偽類 :checked



CSS 偽類選擇器 :checked 表示任何 複選框 (<input type="checkbox">)、單選按鈕 (<input type="radio">)選項 (<option> 在 <select> 中) 元素,這些元素已選中或切換到 開啟 狀態。

此狀態可以透過選中/選擇或取消選中/取消選擇元素來啟用或停用。

語法

:checked {
   /* ... */
}

CSS :checked 示例

以下是一個 :checked 偽類用於 單選按鈕 的示例。當單選按鈕被選中或勾選時,選中的單選按鈕周圍會應用盒陰影樣式。

<html>
<head>
<style>
   div {
      margin: 10px;
      padding: 10px;
      font-size: 20px;
      border: 3px solid black;
      width: 200px;
      height: 45px;
      box-sizing: border-box;
   }

   input[type="radio"]:checked {
      box-shadow: 0 0 0 8px red;
   }
</style>
</head>
<body>
   <h2>:checked example - radio</h2>
   <div>
      <input type="radio" name="my-input" id="yes">
      <label for="yes">Yes</label>
      <input type="radio" name="my-input" id="no">
      <label for="no">No</label>
   </div>
</body>
</html>

以下是一個 :checked 偽類用於 複選框 的示例。當複選框被選中時,盒陰影樣式以及顏色和邊框樣式將應用於複選框及其標籤。

<html>
<head>
<style>
   div {
      margin: 10px;
      font-size: 20px;
   }

   input:checked + label {
      color: royalblue;
      border: 3px solid red;
      padding: 10px;
   }

   input[type="checkbox"]:checked {
      box-shadow: 0 0 0 6px pink;
   }
</style>
</head>
<body>
   <h2>:checked example - checkbox</h2>
   <div>
      <p>Check and uncheck me to see the change</p>
      <input type="checkbox" name="my-checkbox" id="opt-in">
      <label for="opt-in">Check!</label>
   </div>
</body>
</html>

以下是一個 :checked 偽類用於 選項 的示例。當從列表中選擇一個選項時,背景顏色將更改為淺黃色,字型顏色將更改為紅色。

<html>
<head>
<style>
   select {
      margin: 10px;
      font-size: 20px;
   }

   option:checked {
      background-color: lightyellow;
      color: red;
   }
</style>
</head>
<body>
   <h2>:checked example - option</h2>
   <div>
   <h3>Ice cream flavors:</h3>
      <select name="sample-select" id="icecream-flav">
         <option value="opt3">Butterscotch</option>
         <option value="opt2">Chocolate</option>
         <option value="opt3">Cream n Cookie</option>
         <option value="opt3">Hazelnut</option>
         <option value="opt3">Roasted Almond</option>
         <option value="opt1">Strawberry</option>
      </select>
   </div>   
</body>
</html>
廣告