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

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

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

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

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

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

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


当前回答

位置:相对;在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中工作。

其他回答

谢谢!这也一直让我发疯。

在我的特殊情况下,这对我很有用:

input {
    width: 13px;
    height: 13px;
    padding: 0;
    margin:0;
    vertical-align: top;
    position: relative;
    *top: 1px;
    *overflow: hidden;
}
label {
    display: block;
    padding: 0;
    padding-left: 15px;
    text-indent: -15px;
    border: 0px solid;
    margin-left: 5px;
    vertical-align: top;
}

我正在使用reset.css,这可能会解释一些差异,但这似乎对我很有用。

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

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

尝试垂直对齐:中间

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

根据One Crayon的解决方案,我有一些适合我的更简单的方法:

.font2{font-family:Arial;字体大小:32px}/*示例字体*/输入[type=复选框],输入[type=radio]{垂直对齐:中间;位置:相对;底部:1px;}输入[类型=无线电]{底部:2px;} <label><input-type=“checkbox”/>标签文本</label><p class=“font2”><label><input-type=“checkbox”/>标签文本</label></p>

在Safari(我相信它的基线)中,像素对像素的渲染是一样的,Firefox和IE7都很好。它还适用于各种大小的标签字体。现在,为了修复IE在选择和输入上的基线。。。


更新:(第三方编辑)

正确的底部位置取决于字体系列和字体大小!我发现使用底部:.08em;对于checkbox和radio元素是一个很好的通用值。我在Chrome/Firefox/IE11中使用Arial&Calibri字体在windows中使用几种小/中/大字体进行了测试。

.font2,.font2输入{font-family:Arial;字体大小:32px}/*示例字体*/输入[type=复选框],输入[type=radio]{垂直对齐:中间;位置:相对;底部:.08em;/*对于不同的字体,这是一个更好的值*/}<label><input-type=“checkbox”/>标签文本</label><p class=“font2”><label><input-type=“checkbox”/>标签文本</label></p>

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