我该如何更改Bootstrap 4开关按钮的“选中”背景颜色?

10
我无法弄清如何更改Bootstrap 4切换开关的“checked”背景颜色。 它使用额外的库来切换深色和浅色模式-在这里 on github - 但那个是可行的。 我想做的就是更改默认情况下为蓝色的活动复选框的背景颜色。 它是否从Bootstrap CSS默认为蓝色? 这个答案Change Bootstrap 4 checkbox background color对我不起作用; 它只更改未选中的颜色,但我无法从中找到如何更改“checked”颜色的grep信息。

点此查看演示

我的代码:

.custom-control-input {
  background-color: red;
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<div class="custom-control custom-switch">
  <input type="checkbox" class="custom-control-input" id="darkSwitch" />
  <label class="custom-control-label" for="darkSwitch">Dark Mode</label>
</div>

2个回答

12
你可以简单地更改可能影响颜色的所有属性,如.custom-control-input:checked.custom-control-label::before.custom-control-input:active.custom-control-input:focus,但是你必须注意修改.custom-control-input::after,因为它会破坏切换开关内部的指针。

示例

.custom-control-input:focus~.custom-control-label::before {
  border-color: red !important;
  box-shadow: 0 0 0 0.2rem rgba(255, 47, 69, 0.25) !important;
}

.custom-control-input:checked~.custom-control-label::before {
  border-color: red !important;
  background-color: red !important;
}

.custom-control-input:active~.custom-control-label::before {
  background-color: red !important;
  border-color: red !important;
}

.custom-control-input:focus:not(:checked)~.custom-control-label::before {
  border-color: red !important;
}

.custom-control-input-green:not(:disabled):active~.custom-control-label::before {
  background-color: red !important;
  border-color: red !important;
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<div class="custom-control custom-switch">
  <input type="checkbox" class="custom-control-input" id="darkSwitch" />
  <label class="custom-control-label" for="darkSwitch">Dark Mode</label>
</div>


谢谢!这很有效。有没有办法在激活时去掉蓝色边框?我在开发工具中没有看到边框CSS。 - BlueDogRanch
如果你想让 box-shadow 保留,你可以轻松地在我的代码中删除那些 box-shadow,但我认为这不是一个好主意,因为它看起来有点丑。 - Umutambyi Gad
有趣的是,在我的网站上删除它并不能去掉蓝色的盒子阴影。 - BlueDogRanch
我该如何将“已选中”框的阴影或边框更改为红色? - BlueDogRanch
我尝试了所有可能的方法,但是在这段代码片段中仍然显示蓝色的 box-shadow,但在我的Chrome浏览器中却有效。 - Umutambyi Gad
显示剩余4条评论

7
只需将以下内容添加到CSS文件中,或将其添加到HTML文件的 <style> ... </style> 之间即可更改开关的背景颜色 - 这还会删除蓝色圆圈和阴影。=]
.form-switch .form-check-input {
    height: 24px;
    width: 48px;
}
.form-switch .form-check-input:focus {
    border-color: rgba(0, 0, 0, 0.25);
    outline: 0;
    box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
    background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba(0,0,0,0.25)'/></svg>");
}
.form-switch .form-check-input:checked {
    background-color: #30D158;
    border-color: #30D158;
    border: none;
    background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba(255,255,255,1.0)'/></svg>");
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接