自定义复选框在选中时会稍微移动

ste*_*ste 5 html css checkbox

我修改了项目中的复选框,使其看起来与设计的其余部分更加一致,但是我遇到了一个问题:无论何时选中,复选框的标签都会稍微移动。

input[type="checkbox"] {
  display: none !important;
}

input[type="checkbox"]+label:before {
  position: relative;
  content: " ";
  display: inline-block;
  width: 22px;
  height: 22px;
  border: 1px solid grey;
  top: 4px;
  margin: 0 10px 0 0;
}

input[type="checkbox"]:checked+label:before {
  position: relative;
  content: "?";
  display: inline-block;
  width: 22px;
  height: 22px;
  border: 1px solid grey;
  top: 4px;
  margin: 0 10px 0 0;
}
Run Code Online (Sandbox Code Playgroud)
<input type="checkbox" />
<label>Click to accept</label>
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此处输入图片说明

如果选择它,将会发生以下情况:

在此处输入图片说明

我究竟做错了什么?

dip*_*pas 8

现在和一段时间内,如果您将父级设置为display:flex

\n

\r\n
\r\n
input[type="checkbox"] {\n  display: none !important;\n}\n\nlabel {\n  display: flex;\n  /* just to vertically the text with the box */\n  align-items: center\n}\n\ninput[type="checkbox"]+label::before {\n  content: "";\n  display: block;\n  width: 22px;\n  height: 22px;\n  border: 1px solid grey;\n  margin: 0 10px 0 0;\n}\n\ninput[type="checkbox"]:checked+label::before {\n  content: "\xe2\x9c\x94";\n  /* just to center inside the box */\n  display: grid;\n  place-content: center;\n}
Run Code Online (Sandbox Code Playgroud)\r\n
<input id="input" type="checkbox" />\n<label for="input">Click to accept</label>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

旧答案

\n

要解决“移动”问题,您需要:

\n
    \n
  • 设置vertical-align: some valuelabel::before 我已选择bottom
  • \n
\n

要对齐“\xe2\x9c\x94”(如果没有对齐 - 代码片段不是),您需要:

\n
    \n
  • 添加text-align:centerline-height:22px(与height:checked+label::before
  • \n
\n

\r\n
\r\n
input[type="checkbox"] {\n  display: none !important;\n}\n\ninput[type="checkbox"]+label::before {\n  position: relative;\n  content: " ";\n  display: inline-block;\n  vertical-align: bottom;\n  width: 22px;\n  height: 22px;\n  border: 1px solid grey;\n  top: 4px;\n  margin: 0 10px 0 0;\n}\n\ninput[type="checkbox"]:checked+label::before {\n  content: "\xe2\x9c\x94";\n  text-align: center;\n  line-height: 22px;\n}
Run Code Online (Sandbox Code Playgroud)\r\n
<input id="input" type="checkbox" />\n<label for="input">Click to accept</label>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n


\n

注意:在两个答案中,我都删除了重复的属性,并且您缺少要在输入中匹配的for属性,否则您无法单击伪属性labelidcheckbox,只能在label

\n