【问题标题】:Cannot set background color for unchecked checkbox无法为未选中的复选框设置背景颜色
【发布时间】:2019-11-11 04:54:35
【问题描述】:

我正在尝试将未选中复选框的背景颜色设置为白色,但我找不到方法。它在选中和未选中时也保持蓝色。我试过了:

input[type=checkbox]:not(:checked) {
    background-color: white;
}

还有:

input[type=checkbox]:after { (this one I don't think it's even valid)
    background-color: white;
}

我目前的代码是:

input[type=checkbox] {
  position: relative;
  cursor: pointer;
}

input[type=checkbox]:before {
  content: "";
  display: block;
  position: absolute;
  width: 16px;
  height: 16px;
  top: 0;
  left: 0;
  border: 1px solid #99AFC1;
  border-radius: 3px;
  background-color: #00AEEF;
  padding: 1px;
}

input[type=checkbox]:checked:after {
  content: "";
  display: block;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
  position: absolute;
  top: 2px;
  left: 6px;
}
<div class="container">
  <input type="checkbox" name="test">
</div>

如果有人有任何想法,我将不胜感激。谢谢

【问题讨论】:

标签: css checkbox


【解决方案1】:

这是基于您的代码的示例解决方案:

input[type=checkbox] {
  position: relative;
  cursor: pointer;
}

input[type=checkbox]:before {
  content: "";
  position: absolute;
  width: 16px;
  height: 16px;
  top: 0;
  left: 0;
  border: 1px solid #99AFC1;
  border-radius: 3px;
  padding: 1px;
  background-color: #FFFFFF;
}

input[type=checkbox]:checked:before {
  background-color: #00AEEF;
}

input[type=checkbox]:checked:after {
  content: "";
  display: block;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
  position: absolute;
  top: 2px;
  left: 6px;
}
<div class="container">
    <input type="checkbox" name="test">
</div>

【讨论】:

  • 但请注意,appearance 仍处于试验阶段。来自MDN:“如果你想在网站上使用这个属性,你应该非常仔细地测试它。虽然大多数现代浏览器都支持它,但它的实现差异很大。在旧浏览器中,即使是关键字 none 也不相同对跨不同浏览器的所有表单元素的影响,有些根本不支持。在最新的浏览器中差异更小。”
  • 感谢您的反馈!或者,OP 可以为未选中的 ::before 使用白色背景来覆盖默认的复选框外观,也许我会用这种方法更新答案
【解决方案2】:

将以下样式添加到您的 css:

input[type=checkbox]:checked::before {
  background-color: #00AEEF;
}

JsFiddle LINK

希望这会有所帮助。

【讨论】:

  • 非常感谢您的回复,是的,您的解决方案也有效:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-07
  • 1970-01-01
  • 1970-01-01
  • 2013-11-29
  • 2012-12-22
相关资源
最近更新 更多