是否可以使用CSS设置此<label>的样式?

时间:2016-07-17 22:18:12

标签: css css3 checkbox radio-button

我遇到了JS的多个问题,它们改变了单选按钮和图像复选框,并改变了所选单选按钮和复选框上文本的字体。我以为我无法改变HTML的结构,所以我一直在寻找解决方法,但在看到我只用CSS修复所有内容之后,我发现了一种改变HTML结构的方法,这很简单CSS代码修复了一切。惊人的。

input[type=checkbox]:not(old),
input[type=radio   ]:not(old){
  padding: 0;
  opacity: 0;
  filter:alpha(opacity=0);
}

input[type=checkbox]:not(old) + label{
  display: inline-block;
  background: url('images/checkbox-blue.png') no-repeat 0 1px;
  padding-left: 25px;
  margin-left: -15px;
}

input[type=radio]:not(old) + label{
  display: inline-block;
  background: url('images/radio-blue.png') no-repeat 0 1px;
  padding-left: 25px;
  margin-left: -15px;
}

input[type=checkbox]:not(old):checked + label{
  background-position: 0 -18px;
  padding-left: 25px;
  font-weight: bold;
  margin-left: -15px;
}

input[type=radio]:not(old):checked + label{
  background-position: 0 -19px; 
  padding-left: 25px;
  font-weight: bold;
  margin-left: -15px;
}

我的问题:如果输入在标签内,是否可以使用此CSS设置单选按钮和复选框的样式,如下所示?

<label> <input></input> Label text </label>

我问的原因是因为我必须在CSS图像上添加负左边距,以便它们覆盖隐藏的复选框和单选按钮。当浏览器最小化到一定程度时,我必须删除此左边距并添加负上边距以使图像与隐藏的复选框和单选按钮对齐。

如果我可以将输入放在标签内,我认为它可以解决这个问题。

2 个答案:

答案 0 :(得分:1)

当标签位于输入框旁边时,您只能使用+~选择器,因为没有上一个/父选择器。但是,如果有帮助,您可以将文本换行到跨度并为跨度添加样式。否则,您将需要使用Javascript。

input[type=checkbox]:checked + label {
  color: red;
}

input[type=checkbox]:checked + span {
  color: blue;
}
<input id="test" type="checkbox">
<label for="test">Label text</label>

<hr>

<label>
  <input id="test" type="checkbox">
  <span>Label text</span>
</label>

答案 1 :(得分:0)

如果您的网站已包含任何字体图标库,则可以使用字体图标来实现样式设置。图像背景不能扩展或可定制。

看看这个,https://lokesh-coder.github.io/pretty-checkbox/

谢谢

相关问题