html - 自定义复选框在选中时会轻微移动

标签 html css checkbox

I modified the checkboxes in my project to look more aligned with the rest of the design but I have a problem: whenever selected the label of the checkbox moves slightly.

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;
}
<input type="checkbox" />
<label>Click to accept</label>

结果如下:

enter image description here

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

enter image description here

我做错了什么?

最佳答案

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

  • label::before 中设置 vertical-align: some value 我选择了 bottom

要对齐“✔”(以防它不对齐 - 片段不对齐),您需要:

  • :checked+label中添加text-align:centerline-height:22px(与height相同)::之前

我还删除了不必要的重复属性

注意:label中缺少for属性来匹配input中的id,否则无法点击伪checkbox,只在label

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

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

input[type="checkbox"]:checked+label::before {
  content: "✔";
  text-align: center;
  line-height: 22px;
}
<input id="input" type="checkbox" />
<label for="input">Click to accept</label>

关于html - 自定义复选框在选中时会轻微移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45978374/

相关文章:

javascript - 我的模态框相互重叠,当点击两个时,它会触发相同的内容

html - 带有单独滚动条的固定位置侧边栏?

php - PHP & Mysql 多复选框功能

javascript - Asp.net MVC 根据值检查/取消选中复选框?

Jquery从复选框中获取多个选中值

html - 如何使用CSS中的边距属性将Div元素放在中心

php - 在ckeditor上打开+编辑html文件

css - Z-index 在 iframe IE8 和 IE7 中不起作用

javascript - 我的 if 语句不起作用

python - 将 Pandas 数据框传递给 Django 模板