复选标记转义复选框



我正试图编写CSS代码来模拟和设置复选框的样式,因为input type="checkbox"无法设置样式。

这是我的HTML和CSS:

label > input[type="checkbox"] + span::before {
content: "✓";
width: 20pt;
height: 20pt;
border-radius: 10%;
border-style: solid;
border-width: 0.1rem;
border-color: gray;
display: inline-block;
vertical-align: middle;
}
<label>
<input type="checkbox" name="pos[]" value="shirt" />
<span> shirt </span>
<br>
</label>

我想要的行为是:

  • 空正方形垂直居中
  • 方格内有复选标记

正方形居中,但复选标记";✓"停留在底部,与复选框右侧的文本处于同一级别。我尝试过displayvertical-align的不同组合,但都没有效果。如何将复选标记居中?

您可以使用text-align: center水平对齐中心,使用line-height: {number}px垂直对齐。我建议您使用弹性框来更有效地管理对齐。但对于你的例子,你可以按照我的例子:

label > input[type="checkbox"] {
display: none;
}
label > input[type="checkbox"] + span::before {
content: "✓";
width: 20pt;
height: 20pt;
border-radius: 10%;
border-style: solid;
border-width: 0.1rem;
border-color: gray;
line-height: 28px;
text-align: center;
display: inline-block;
vertical-align: middle;


} 
label > input[type="checkbox"]:checked + span::before {
content: ' ';
}
<label>
<input type="checkbox" name="pos[]" value="shirt" />
<span> shirt </span>
<br>
</label>

我认为您的代码应该是这样的

label > input[type="checkbox"] + span {
position: relative;
width: 17px;
height: 17px;
border-radius: 10%;
border-style: solid;
border-width: 0.1rem;
border-color: gray;
display: inline-block;
vertical-align: middle;
} 
label > input[type="checkbox"] {
display: none
} 
label > input[type="checkbox"]:checked + span::before {
content: "✓";
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
} 
label  {
padding
}
<label>
<input type="checkbox" name="pos[]" value="shirt" />
<span></span>
<span> shirt </span>
<br>
</label>

最新更新