How to align checkboxes and their labels consistently cross
This is one of the minor CSS problems that plagues me constantly. How do folks around Stack Overflow vertically align checkboxes
and their labels
consistently cross-browser ? Whenever I align them correctly in Safari (usually using vertical-align: baseline
on the input
), they're completely off in Firefox and IE. Fix it in Firefox, and Safari and IE are inevitably messed up. I waste time on this every time I code a form.
Here's the standard code that I work with:
<form>
<div>
<label><input type="checkbox" /> Label text</label>
</div>
</form>
After over an hour of tweaking, testing, and trying different styles of markup, I think I may have a decent solution. The requirements for this particular project were:
Before I get into any explanation, I'll just give you the code:
label {
display: block;
padding-left: 15px;
text-indent: -15px;
}
input {
width: 13px;
height: 13px;
padding: 0;
margin:0;
vertical-align: bottom;
position: relative;
top: -1px;
*overflow: hidden;
}
<form>
<div>
<label><input type="checkbox" /> Label text</label>
</div>
</form>
Sometimes vertical-align needs two inline (span, label, input, etc...) elements next to each other to work properly. The following checkboxes are properly vertically centered in IE, Safari, FF, and Chrome, even if the text size is very small or large.
They all float next to each other on the same line, but the nowrap means that the whole label text always stays next to the checkbox.
The downside is the extra meaningless SPAN tags.
.checkboxes label {
display: block;
float: left;
padding-right: 10px;
white-space: nowrap;
}
.checkboxes input {
vertical-align: middle;
}
.checkboxes label span {
vertical-align: middle;
}
<form>
<div class="checkboxes">
<label for="x"><input type="checkbox" id="x" /> <span>Label text x</span></label>
<label for="y"><input type="checkbox" id="y" /> <span>Label text y</span></label>
<label for="z"><input type="checkbox" id="z" /> <span>Label text z</span></label>
</div>
</form>
从一个蜡笔小新的解决方案中脱颖而出,我有一些适合我的东西,而且更简单:
input[type=checkbox], input[type=radio] {
vertical-align: middle;
position: relative;
bottom: 1px;
}
input[type=radio] {
bottom: 2px;
}
<label>
<input type="checkbox">
Label text
</label>
链接地址: http://www.djcxy.com/p/1092.html
上一篇: 如何垂直居中所有浏览器的div?
下一篇: 如何对齐复选框及其标签始终交叉