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

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

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

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

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

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

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


当前回答

我找到了一种在几乎所有浏览器中都能得到相同结果的方法。至少是最新的浏览器。它适用于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 */
}

其他回答

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

vertical-align: middle

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

输入类型复选框包装在标签内并向左浮动,如下所示:

<label for="id" class="checkbox">
    <input type="checkbox" id="id">
    <span>The Label</span>
</label>

这对我有用:

label.checkbox {
    display: block;
}
.checkbox input {
    float: left;
    height: 18px;
    vertical-align: middle;
}
.checkbox span {
    float: left;
    line-height: 18px;
    margin: 0 0 0 20px;
}

确保的高度与(块级别)的线高度相同。

尝试垂直对齐:中间

而且你的代码看起来应该是:<表单><div><input id=“blah”type=“checkbox”><label for=“blah“>标签文本</label></div></form>

input {
    margin: 0;
}

真的很管用

位置:相对;在IE中的z索引和jQuery的slideUp/slideDown等动画存在一些问题。

CSS:

input[type=checkbox], input[type=radio] {
    vertical-align: baseline;
    position: relative;
    top: 3px;
    margin: 0 3px 0 0;
    padding: 0px;
}
input.ie7[type=checkbox], input.ie7[type=radio] {
    vertical-align: middle;
    position: static;
    margin-bottom: -2px;
    height: 13px;
    width: 13px;
}

jQuery:

$(document).ready(function () {
    if ($.browser.msie && $.browser.version <= 7) {
        $('input[type=checkbox]').addClass('ie7');
        $('input[type=radio]').addClass('ie7');
    }
});

样式可能需要根据<label>中使用的字体大小进行调整

PS(秒):我使用ie7js使css在IE6中工作。