CSS Checkboxes,如何处理所需

时间:2017-06-22 08:45:57

标签: css checkbox required-field

我正在使用此HTML交换我自己的浏览器复选框

input[type="checkbox"] {
  display: none;
  width: 30px;
  &+label {
    width: 30px;
    &::before {
      display: inline-block;
      width: 30px;
      height: 26px;
      margin: 0px;
      vertical-align: middle;
      background: url(../images/tick.png) -30px top no-repeat;
      cursor: pointer;
      content: "";
    }
  }
  &:checked+label::before {
    background: url(../images/tick.png) left top no-repeat;
  }
}
<input required type="checkbox" id="acceptance" name="acceptance" value="yes"><label for="acceptance"></label>

3 个答案:

答案 0 :(得分:0)

您正在使用:before向标签显示勾选/交叉图像,具体取决于复选框:checked设置。对:after执行相同的操作:

input[type="checkbox"] {
    &[required] + label:after {
        content: "*";
        color: red;
    }
}

答案 1 :(得分:0)

您不需要label。您可以直接将:before元素添加到复选框输入(确保进行跨浏览器检查。不确定兼容性。)

任何符合html5标准的浏览器都会弹出说明该元素是必需的:

HTML5 Compliant browser prompt informing required element is not checked

由于我没有图片,我将未经检查的颜色更改为红色,并将选中的颜色更改为蓝色:

&#13;
&#13;
input[type="checkbox"] {
  width: 30px;
}

input[type="checkbox"]::before {
  display: inline-block;
  width: 30px;
  height: 26px;
  margin: 0px;
  vertical-align: middle;
  background: url(../images/tick.png) -30px top no-repeat red;
  cursor: pointer;
  content: "";
}

input[type="checkbox"]:checked::before {
  background: url(../images/tick.png) left top no-repeat blue;
}
&#13;
<form>
<input required type="checkbox" id="acceptance" name="acceptance" value="yes">
<input type="submit" />
</form>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

由于我也遇到这种问题,并且找到了较新的解决方案,因此我将在这里分享

https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation#Using_built-in_form_validation

现在我们有:valid:invalid伪类

例如:

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

希望有帮助