CSS如何使用:checked伪类

66次阅读
没有评论

在CSS中,:checked 伪类可以选择已经被选中的表单控件(例如复选框或单选框)。以下是如何在CSS中使用:checked伪类的步骤:

  1. 选择要应用样式的表单控件。
  2. 在选择器中添加:checked伪类。

例如,要选择所有已经被选中的复选框并更改它们的背景颜色,可以使用以下CSS代码:

input[type="checkbox"]:checked {
  background-color: yellow;
}

这将选择所有已经被选中的复选框,并将它们的背景颜色更改为黄色。

以下是一个完整的HTML5页面示例,其中包含一个使用:checked伪类的CSS样式表:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>:checked Example</title>
  <style>
    /* Select all checked checkboxes and change their background color */
    input[type="checkbox"]:checked {
      background-color: yellow;
    }
  </style>
</head>
<body>
  <h2>Choose your favorite fruits:</h2>
  <form>
    <input type="checkbox" id="apple" name="fruit" value="apple">
    <label for="apple">Apple</label><br>
    <input type="checkbox" id="banana" name="fruit" value="banana">
    <label for="banana">Banana</label><br>
    <input type="checkbox" id="orange" name="fruit" value="orange">
    <label for="orange">Orange</label><br>
  </form>
</body>
</html>

在这个例子中,我们使用CSS选择器 input[type=”checkbox”]:checked 选择了所有已经被选中的复选框,并将它们的背景颜色更改为黄色。这样就可以通过视觉效果来强调哪些复选框已经被选中。

正文完
 
评论(没有评论)