【问题标题】:Styling checkbox using CSS使用 CSS 设置复选框样式
【发布时间】:2017-02-15 10:26:04
【问题描述】:

我正在尝试在表单上设置自定义复选框的样式;我的 HTML 看起来像这样:

<form id="contact">
  <input type="checkbox" id="option1" />
  <label for="option1">Option</label>
</form>

我的 CSS 看起来像这样:

form input[type="checkbox"] {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0.2;
}
form label {
  padding-left: 20px;
  position: relative;
}
form label:before {
  content: "";
  width: 20px;
  height: 20px;
  position: absolute;
  left: -10px;
  border: 1px solid #000;
}

我想在勾选复选框时添加背景颜色,所以我添加了这条规则:

input[type="checkbox"]:checked + label:before {
  background-color: #ccc;
}

按照我的意愿工作,但我只需要具体说明规则才能在联系表单上工作,因此我将其更改为:

#contact input[type="checkbox"]:checked + #contact label:before {
  background-color: #ccc;
}

这次不行。勾选复选框时背景不会改变。

我的问题是 CSS 有什么问题?我错过了什么?

【问题讨论】:

标签: html css checkbox


【解决方案1】:

你们很亲密。选择器应该是:

#contact input[type="checkbox"]:checked + label:before {
  background-color: #ccc;
}

它不起作用的原因是#contact 不是与input[type="checkbox"] 元素相邻的兄弟。您需要省略第二个#contact id 选择器。

换句话说,选择器:

input[type="checkbox"]:checked + #contact label {}

将尝试选择以下label 元素:

<input type="checkbox" id="option1" />
<div id="#contact">
   <label for="option1">Option</label>
</div>

由于input 复选框元素没有相邻的#contact 元素,因此没有选择任何内容。

【讨论】:

  • 感谢您的快速回复,伙计!效果很好。
【解决方案2】:

form input[type="checkbox"] {
    position: absolute;
    left: 0;
    top: 0; opacity: 0; }

form label {
    padding-left: 30px;
    position: relative; }

form  label:before {
    content: "";
    width: 20px;
    height: 20px;
    position: absolute;
    left: 0;
    top: 0;
    border: 1px solid #000; }
    
    #contact input[type="checkbox"]:checked + label:before { background-color: #ccc; }
<form id="contact">
       <input type="checkbox" id="option1" />
       <label for="option1">Option</label>
   </form>

请更新此代码#contact input[type="checkbox"]:checked + label:before { background-color: #ccc; }

【讨论】:

  • 这与我 3 小时前发布的内容有何不同?
  • 你在这里做错了prntscr.com/9sdt1i你已经指定了正确的选择器所以删除beore +标签选择器
猜你喜欢
  • 1970-01-01
  • 2010-12-12
  • 2014-06-11
  • 2013-06-09
  • 2014-09-14
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
相关资源
最近更新 更多