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

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

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

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

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

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

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


当前回答

尝试垂直对齐:中间

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

其他回答

<fieldset class="checks">
    <legend>checks for whatevers</legend>
    <input type="" id="x" />
    <label for="x">Label</label>
    <input type="" id="y" />
    <label for="y">Label</label>
    <input type="" id="z" />
    <label for="z">Label</label>
</fieldset>

无论如何,您应该将分组在一起的表单控件包装在它们自己的字段集中,在这里,它播放包装。设置输入/标签显示:块,输入浮动左,标签浮动右,设置宽度,控制左右边距的间距,相应地对齐标签文本。

so

fieldset.checks {
    width:200px
}
.checks input, .checks label {
    display:block;
}
.checks input {
    float:right;
    width:10px;
    margin-right:5px
}
.checks label {
    float:left;
    width:180px;
    margin-left:5px;
    text-align:left;
    text-indent:5px
}

对于跨浏览器/媒体解决方案,您可能需要同时设置边框、轮廓和线条高度。

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

<form>
  <div>
    <input type="checkbox" id="cb" /> <label for="cb">Label text</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 */
}

我发现唯一能将它们对齐的方法是使用绝对位置作为输入。摆弄输入的顶部变量得到了我想要的结果。

div {
  clear:    both;
  float:    none;
  position: relative;
}

input {
  left:     5px;
  position: absolute;
  top:      3px;
}

label {
  display:     block;
  margin-left: 20px;
}

有时垂直对齐需要两个相邻的内联(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>