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

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

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

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

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

<表单><div><label><input-type=“checkbox”/>标签文本</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

这不是解决问题的最佳方式

vertical-align: middle

将style=“position:relative;top:2px;”添加到输入框会将其向下移动2px。因此,根据您的字体大小,您可以移动它。

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

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

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

复选框标签{显示:内联块;右侧填充:10px;空白:nowrap;}复选框输入{垂直对齐:中间;}复选框标签跨度{垂直对齐:中间;}<表单><div class=“checkbox”><label><inputtype=“checkbox”><span>标签文本x</span></label><label><input-type=“checkbox”><span>标签文本y</span></label><label><input-type=“checkbox”><span>标签文本z</span></label></div></form>

现在,如果您有一个非常长的标签文本需要在复选框下换行而不换行,那么您可以在标签元素上使用填充和负文本缩进:

复选框标签{显示:块;右侧填充:10px;向左填充:22px;文本缩进:-22px;}复选框输入{垂直对齐:中间;}复选框标签跨度{垂直对齐:中间;}<表单><div class=“checkbox”><label><input-type=“checkbox”><span>给文本x加上很长的标签,使其可能会换行,让我们看看它如何与建议的CSS(预期:两行很好地对齐)</span></label><label><input-type=“checkbox”><span>标签文本y</span></label><label><input-type=“checkbox”><span>标签文本z</span></label></div></form>

CSS:

.threeCol .listItem {
    width:13.9em;
    padding:.2em;
    margin:.2em;
    float:left;
    border-bottom:solid #f3f3f3 1px;
}
.threeCol input {
    float:left;
    width:auto;
    margin:.2em .2em .2em 0;
    border:none;
    background:none;
}
.threeCol label {
    float:left;
    margin:.1em 0 .1em 0;
}

HTML格式:

<div class="threeCol">
    <div class="listItem">
        <input type="checkbox" name="name" id="id" value="checkbox1" />
        <label for="name">This is your checkBox</label>
    </div>
</div>

上面的代码将把你的列表项放在三列中,只需改变宽度即可。

尝试此代码

input[type="checkbox"] {
    -moz-appearance: checkbox;
    -webkit-appearance: checkbox;
    margin-left:3px;
    border:0;
    vertical-align: middle;
    top: -1px;
    bottom: 1px;
    *overflow: hidden;
    box-sizing: border-box; /* 1 */
    *height: 13px; /* Removes excess padding in IE 7 */
    *width: 13px;
    background: #fff;
}