css 复选框中伪 class 的位置不起作用

css position for pseudo class in checkbox not working

我需要使用 CSS 而不是图像在复选框中创建一个勾号。

我可以看到正确显示绿色“✔”。但是 css 中的顶部和左侧不起作用,勾号总是卡在复选框的左上角,我希望它在中间。为什么内容和颜色 属性 有效但左侧和顶部无效?

Top 和 left 不适用于静态元素,您需要指定相对、固定或绝对位置才能使用这些 属性。你可以试试这个:

input[type=checkbox]:checked ~ .icon:after, ._checked input[type=checkbox] ~ .icon :after {
    background-position: 0 -800px;
    content: '✔';
    font-size: 25px;
    margin: auto;
    top: 15px;
    left: 250px;
    color: green;
    position: relative;
}

完整代码:

input[type=checkbox]:focus+.icon {
  background-position: 0 -822px;
}

input[type=checkbox]:checked~.icon,
._checked input[type=checkbox]~.icon {
  background-position: 0 -856px;
  background-color: #2196F3;
  display: block;
}

input[type=checkbox]:checked~.icon:after,
._checked input[type=checkbox]~.icon :after {
  background-position: 0 -800px;
  content: '✔';
  font-size: 25px;
  margin: auto;
  top: 5px;
  left: 50%;
  margin-left:-12px;
  color: green;
  position:relative;
}

input[type=checkbox]:not(:checked)+div.validationsContainer~.icon {
  background-position: 0 -890px;
}

,
input[type=checkbox]:checked:hover+label,
input[type=checkbox]:checked:focus+label {
  background-position: 0 15.3%;
}

&.hasError .icon {
  background-position: 0 -890px;
}
<input type="checkbox" required="required" name="terms" id="termsAgree" auto-required="true">
<span class="icon"></span>