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

Stack Overflow周围的人如何在浏览器中始终垂直对齐复选框及其标签?

每当我在Safari中正确对齐它们(通常在输入上使用垂直对齐:基线),它们在Firefox和IE中就完全关闭了。

在Firefox中修复它,Safari和IE不可避免地被搞砸了。我每次编写表单时都在这上面浪费时间。

以下是我使用的标准代码:

<表单><div><label><input-type=“checkbox”/>标签文本</label></div></form>

我通常使用埃里克·迈耶的重置,所以表单元素相对来说没有覆盖。期待您提供的任何提示或技巧!


当前回答

一个看起来很好用的简单方法是使用垂直对齐调整复选框的垂直位置。它仍然会因浏览器而异,但解决方案并不复杂。

input {
    vertical-align: -2px;
}

参考

其他回答

正如pokrishka已经建议的那样,简单地使用垂直对齐:sub。

不停摆弄

HTML代码:

<div class="checkboxes">
    <label for="check1">Test</label>
    <input id="check1" type="checkbox"></input>
</div>

CSS代码:

.checkboxes input {
    vertical-align: sub;
}

我找到了一种在几乎所有浏览器中都能得到相同结果的方法。至少是最新的浏览器。它适用于Firefox、Chrome、Safari和Opera。在IE中,它看起来就像没有对输入或标签应用规则一样(即,它的标签仍然比输入低几个像素),所以我认为这是可以理解的。

HTML

<label class="boxfix"><input type="radio">Label</label>

CSS

.boxfix {
    vertical-align: bottom;
}
.boxfix input {
    margin: 0;
    vertical-align: bottom;
    position: relative;
    top: 1.999px; /* the inputs are slightly more centered in IE at 1px (they don't interpret the .999 here), and Opera will round it to 2px with three decimals */
}

我从来没有这样做的问题:

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

为了与浏览器中的表单字段保持一致,我们使用:框大小调整:边框框

button, checkbox, input, radio, textarea, submit, reset, search, any-form-field {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

硬编码复选框的高度和宽度,删除其填充,并使其高度加上垂直边距等于标签的行高度。如果标签文本是内联的,请浮动复选框。Firefox、Chrome和IE7+都以相同的方式呈现以下示例:http://www.kornea.com/css-checkbox-align