display: inline-block; A lesser known css property that works!
No more trouble getting the vertical alignments correct. display: inline-block allows you to set a width and height on your elements without forcing a break; you get an inline element which you can set width and height on, just like you can on a block element. Simply set a fixed width on your labels and watch the input fields line up nicely. Details and code examples inside!
Normally you’ll write your html something like this. (One may argue that a form is a list of things to fill out, but I’m using paragraphs for simplicity)
<form> <label for="name">Full name:</label><input id="name" name="name" type="text" />
<label for="email">Email:</label><input id="email" name="email" type="text" />
<label for="phone">Phone number:</label><input id="phone" name="phone" type="text" />
</form>
Result:
Not very pretty, but then we apply this style to all our labels:label { display: inline-block; width: 90px }
W3 has this to say about inline-block
This value causes an element to generate a block box, which itself is flowed as a single inline box, similar to a replaced element. The inside of an inline-block is formatted as a block box, and the element itself is formatted as an inline replaced element.Result: Voila! That’s one pretty form!
Catches
Like all good stuff, there are a few catches: Normally you would expect to see that IE6 or even IE7 doesn’t support this, but this time it’s actually firefox(!) not supporting the inline-block value, at least not the standard value.There’s been a bug report for this since mozilla 1.1 (!), but the good news is that it’s ready for firefox 3. Only took 9 years. In the mean time they have -moz-inline-block which seems to do the trick, so our full label css will look like this.
label { display: -moz-inline-block; display: inline-block; width: 90px; }
Another catch is that IE only supports this property on elements that are inline by default, and only when in standards mode. (I.e this is a no go for those playing in quirks mode) You can however mimick the behaviour on block elements to by giving the elements hasLayout (zoom: 1 for instance), and then setting display: inline.