改变Bootstrap4、Bootstrap5中复选框的颜色

今天做练习,用到了Bootstrap4制作的开关式复选框,复选框默认的颜色是蓝色,跟整个网页颜色不搭,需要改成绿色。
在这里插入图片描述

想从网上找现成的答案,找了几个,试了试居然无效,只好自己来。经过几次尝试,改成功了。我用的版本是Bootstrap4,结果发现Bootstrap5和 Bootstrap4实现起来还不太一样,最后测试可以了。

一、Bootstrap5中的复选框

Bootstrap5中的复选框改变颜色实现起来很容易,只需要直接修改 .form-check-input选中时:checked的背景色和边框颜色就可以了。

  .form-check-input:checked {
    
    
      background-color: #28a745; 
      border-color:#28a745;
    }

完整代码如下:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bootstra5中复选框的颜色</title>
  <link href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  <style> -->
    .form-check-input:checked {
    
    
      background-color: #28a745;
      border-color:#28a745;
    }
  </style> 
  </head>
  <body>
    <div class="container mt-3">
      <div class="form-check">
        <input type="checkbox" class="form-check-input" id="option1" name="sports" value="something" checked>
        <label class="form-check-label" for="check1">羽毛球</label>
      </div>
      <div class="form-check">
        <input type="checkbox" class="form-check-input" id="option2" name="sports" value="something">
        <label class="form-check-label" for="check2">乒乓球</label>
      </div>
    </div>
    <!-- 开关样式的复选框 form-switch -->
    <div class="container mt-3 form-check form-switch">
      <input class="form-check-input" type="checkbox" id="mySwitch" value="yes" checked>
      <label class="form-check-label" for="mySwitch">已启用</label>
    </div>
  </body>
</html>

二、Bootstrap4中的复选框

Bootstrap4中复选框颜色的修改要稍微复杂一点,需要使用~兄弟选择器,还要使用::before,所用的类名也不同。原本我参考的代码写的是:active,经测试无效,我抱着试试看的态度改成了:checked,实现了目标效果哦。直接复制下面代码,改改颜色值即可。代码如下:

    .custom-control-input:checked~.custom-control-label::before{
    
    
      background-color: #28a745;
      border-color: #28a745;
    } 

完整代码如下:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bootstrap4中复选框的颜色</title>
  <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
  <!-- 以下css样式更改复选框的背景色 为绿色-->
  <style>
    .custom-control-input:checked~.custom-control-label::before{
      
      
      background-color: #28a745;
      border-color: #28a745;
    } 
  </style>
</head>
  <body>
    <div class="container">
      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" id="customSwitch1" checked>
        <label class="custom-control-label" for="customSwitch1">网球</label>
      </div>
    <div class="custom-control  custom-switch">
      <input type="checkbox" class="custom-control-input" id="customSwitch2" checked>
      <label class="custom-control-label" for="customSwitch2">已启用</label>
    </div>
  </div>
  </body>
</html>

猜你喜欢

转载自blog.csdn.net/wangyining070205/article/details/126353319