如何跨浏览器一致地对齐复选框及其标签

问题描述

有时垂直对齐需要两个相邻的内联(跨度、标签、输入等)元素才能正常工作。以下复选框在 IE、Safari、FF 和 Chrome 中正确垂直居中,即使文本大小非常小或大。

它们都在同一行上彼此相邻浮动,但 nowrap 意味着整个标签文本始终位于复选框旁边。

缺点是额外无意义的 SPAN 标签。

.checkboxes label {
  display: inline-block;
  padding-right: 10px;
  white-space: nowrap;
}
.checkboxes input {
  vertical-align: middle;
}
.checkboxes label span {
  vertical-align: middle;
}
<form>
  <div class="checkboxes">
    <label><input type="checkbox"> <span>Label text x</span></label>
    <label><input type="checkbox"> <span>Label text y</span></label>
    <label><input type="checkbox"> <span>Label text z</span></label>
  </div>
</form>

现在,如果您有一个很长的标签文本需要在复选框下方不换行,您将在标签元素上使用填充和负文本缩进:

.checkboxes label {
  display: block;
  padding-right: 10px;
  padding-left: 22px;
  text-indent: -22px;
}
.checkboxes input {
  vertical-align: middle;
}
.checkboxes label span {
  vertical-align: middle;
}
<form>
  <div class="checkboxes">
    <label><input type="checkbox"> <span>Label text x so long that it will probably wrap so let's see how it goes with the proposed CSS (expected: two lines are aligned nicely)</span></label>
    <label><input type="checkbox"> <span>Label text y</span></label>
    <label><input type="checkbox"> <span>Label text z</span></label>
  </div>
</form>

解决方法

这是一直困扰我的小 CSS 问题之一。

如何垂直对齐checkboxes以及他们labels始终如一的跨浏览器

每当我在 Safari 中正确对齐它们(通常vertical-align: baseline在 上使用input)时,它们在 Firefox 和 IE 中完全关闭。

在 Firefox 中修复它,Safari 和 IE 难免搞砸了。每次编写表格时,我都会在这上面浪费时间。

这是我使用的标准代码:

<form>
    <div>
        <label><input type="checkbox" /> Label text</label>
    </div>
</form>

我通常使用 Eric Meyer 的重置,因此表单元素相对而言没有覆盖。期待您提供的任何提示或技巧!

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...