Inputs and Labels – a dynamic tester

31 Jan 10   webdev   5 Comments


#test label,
#test input {
position: absolute;
left: 0; top: 0;
margin: 0;
padding: 0.4em 0;
font-family: 'Helvetica', sans-serif;
font-size: 1em;
height: 2em;
border: none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#test label {
background: #1265bb;
line-height: 1.15;
}
#test input {
text-indent: -1px;
opacity: 0.5;
line-height: 1.08;
}

Styling forms is a nightmare. One of the many problems is that inputs, textareas, submit buttons and labels all look different from each other, even inside a single browser. Check this example – a label and an input[type=text] with default styling overlayed on top of one another. Each has a healthy dose of underscores so you can see clearly where the baseline is, and I’ve given the input some transparency to help us:


You see the problem. The input, by default, appears to have margin space surrounding it, and depending which browser you’re in, a different font-family, font-size, padding, height and line-height than the label. Attempting to reset these in CSS gives us:


Actually, that gets pretty close. Webkit and Mozilla still offset horizontally by 1px, but we could possibly cure that with a text-indent: -1px. Try giving these some height and centring the text vertically with line-height, however, and we run into problems. FireFox does not respect line-height for inputs, so we are forced to control vertical alignment with padding:


But even here we see that in Firefox the two baselines move relative to one another when the window resizes and the text re-flows — for no real reason.

I’m convinced there are, however, some magic numbers for combinations of top and bottom padding and line-height that cause less disruption than others. And to dabble in these Dark Arts I’ve made this dynamic inputs and labels tester. Have a play around with the example at the top, using the CSS editor to restyle the test. Resort to whatever canny CSS wizadry you can muster. You can see that I’ve started with the new CSS3 box-sizing property. If you magic your way into any stable combinations that do a decent job of equalising the baseline between inputs and labels, and they work in at least FF / Webkit, post them in the comments.