如何改变type="checkbox"的input复选框的样式

<input type="checkbox">默认的样式是由浏览器控制的,直接修改它的样式比较困难。可以通过一些CSS技巧来实现自定义样式,包括改变颜色。

直接上例子吧:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Custom Checkbox</title>
  <style>
    /* 隐藏原生的checkbox */
    .custom-checkbox input[type="checkbox"] {
      opacity: 0;
      position: absolute;
    }

    /* 自定义样式 */
    .custom-checkbox label {
      display: inline-block;
      width: 20px;
      height: 20px;
      border: 2px solid red;
      border-radius: 4px;
      position: relative;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    /* 当checkbox被选中时的样式 */
    .custom-checkbox input[type="checkbox"]:checked + label {
      background-color: blue; /* 改变选中时的背景颜色 */
    }

    /* 添加一个小勾勾 */
    .custom-checkbox input[type="checkbox"]:checked + label::after {
      content: "";
      position: absolute;
      top: 4px;
      left: 6px;
      width: 8px;
      height: 4px;
      border: 2px solid white;
      border-top: none;
      border-right: none;
      transform: rotate(-45deg);
    }
  </style>

  <style>
    /* 自定义样式 */
    .custom-checkbox input[type="checkbox"] {
      width: 20px;
      height: 20px;
      border: 2px solid #000;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s ease, border-color 0.3s ease;
    }

    /* 当checkbox被选中时的样式 */
    .custom-checkbox input[type="checkbox"]:checked {
      background-color: blue; /* 改变选中时的背景颜色 */
      border-color: blue; /* 改变选中时的边框颜色 */
    }
  </style>
</head>
<body>
  <div class="custom-checkbox">
    <input type="checkbox" id="checkbox1">
    <label for="checkbox1"></label>
  </div>

  <br/>
  <h1>----------------------</h1>
  <div class="custom-checkbox">
    <input type="checkbox" id="checkbox3">
    <label for="checkbox3"></label>
  </div>
</body>
</html>
posted @ 2025-03-26 15:55  smil、梵音  阅读(602)  评论(0)    收藏  举报