February 9, 2006
I learned several advanced and quick methods of styling layout without tables, mainly used for forms, where fields should always be aligned:
inline block
label {display:-moz-inline-box; _display: inline-block}
This effectively pushes the fields to a fixed position on the right of the label, and works in almost all browsers
absolute positioning
Absolute positioning of the forms gives you the possibility to shift the fields to the right using relative positioning, as follows
form {position:relative}
input {position:absolute;left:10em}
float
Last but not least there is floating. This is usually complex because
- the height of labels and fields needs to be equal for correct floating/alignment, and
- the width of label+height should (almost) equal the form width. There should be room for margin/padding/rounding errors/font-size setting (in case of pixel widths)
form {width: 20em}
label {float:left; line-height:1.5em; margin-bottom:.2em; width: 9.5em}
input {float:left; line-height:1.5em; width: 9.5em}
This can however be fixed by adding a little border or padding to the label, assuming both have the same font size, like this:
form {width: 20em}
label {float:left; margin-bottom:1em; width: 10em; padding-right:1px}
input {float:left}
In this solution you can play around with margins as much as you like without messing up the display. If anybody can explain to me why this works please let me know.
update: Ingo Chao explained why it works. The width of the label is exactly half of the form’s width. By adding that 1 pixel, two labels cannot go side by side and thus the next label in row will drop. In the original scenario (no widths, or no extra pixel) the first label moves up, but leaves space on the left, where the next label doesn’t fit, and so it moves down. That doesn’t sound very clear, but I’ll see if I can put an image here soon.
update2: using label {clear:left} fixes the problems too.
October 30, 2006 at 7:09 pm
Hi Michiel,
I enjoyed exploring your floating form elements. I happened to find that in Safari 2.0.4 and in Opera 8.52 the Opt-in checkbox is pushed online up next to the “Calendar” button. In Safari this happens only with larger font sizes, in Opera it seems to be a consistent error.
Still, a great article and great work.
rudolf
November 1, 2006 at 12:36 am
Thanks a lot. Appreciated. Actually I have a lot more to say on the subject now, so a sequel to this article is not a bad idea.
January 14, 2008 at 12:48 am
Hi.
I was wondering how about the HTML form from http://www.dynamicdrive.com/style/csslibrary/item/css-tableless-form/ Where do you type the email address of where the form is being sent to?
Thanks.
January 16, 2008 at 12:11 am
Well Harry, it’s not that simple. You have to combine this with a server side script, e.g. in PHP, where the email address is specified. In PHP you can send email using the mail() function.
April 9, 2008 at 3:07 am
edlkm