【问题标题】:Check mark escapes checkbox复选标记转义复选框
【发布时间】:2021-04-11 00:16:55
【问题描述】:

我正在尝试编写 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 的不同组合,但没有任何效果。如何使复选标记居中?

【问题讨论】:

  • "an input type="checkbox" cannot be stylized" --- 技术上可以,你只需要先在它们上设置appearance: none;(有些浏览器可能不喜欢)跨度>
  • 我还认为这里还有其他 CSS 在起作用,因为我在尝试时得到了 this,一旦插入了 text-align: center,它就开始看起来不太像样了。

标签: html css checkbox


【解决方案1】:

您可以使用text-align: center 水平对齐中心,使用line-height: {number}px 垂直对齐。我建议您使用flex-box 更有效地管理对齐。但是对于您的示例,您可以按照我的示例进行操作:

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>

【讨论】:

  • 这个line-height: 28px; 似乎可以完成这项工作,但我将不得不研究 flex-box 以获得永久性的东西。
  • 是的,我强烈建议您这样做。快乐编码@ToniAz!
【解决方案2】:

我觉得你的代码应该是这样的

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>

【讨论】:

    猜你喜欢
    • 2011-04-14
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    相关资源
    最近更新 更多