[thelist] Tip: Form Layout with CSS

John.Brooking at sappi.com John.Brooking at sappi.com
Fri Sep 17 08:00:43 CDT 2004


Thanks to all who responded to my recent question about laying out a form
without using a table. With the responses and some experimentation, here's
what I learned:

<tip author="John Brooking" type="Form Layout with CSS">

What's the "best" way to lay out a form so that the fields all line up? Many
of us started out using tables, but here is another way, without tables. I
intend to make it my new standard, since IMHO it seems the best combination
of simplicity and semantic correctness. Assume for the sake of explanation
that you have just one form on your page, and all your input fields are one
label/field per line. The model can be easily expanded for more complicated
situations.

Inside your FORM tag, make each label/field pair as follows:

   <LABEL for="fieldName">Field Label: </LABEL>
   <INPUT name="fieldName"> <!-- or SELECT or TEXTAREA -->
   <BR>
   
Now, to style it, just include the following in a STYLE tag or external
sheet:

   LABEL {
      float: left;
      width: 100px; /* or whatever you want */
      vertical-align: top;
   }

The width property causes all labels to be the same width, lining up the
input fields. The tricky part is that LABEL is by default an inline element,
and as such, width is not a supported CSS property for it. (I found that IE
will apply it anyway, but other browsers do not, and the spec does not
require them to.) For that reason, we use the float property to
simultaneously turn LABEL into a block element, so width can be properly
applied, and float it next to its input field so that they are still on the
same line. Just a small hack. The vertical-align setting just ensures that
for TEXTAREA tags, the label is next to the top of the TEXTAREA rather than
the bottom, which it otherwise would.

</tip>

- John
-- 
 

This message may contain information which is private, privileged or
confidential and is intended solely for the use of the individual or entity
named in the message. If you are not the intended recipient of this message,
please notify the sender thereof and destroy / delete the message. Neither
the sender nor Sappi Limited (including its subsidiaries and associated
companies) shall incur any liability resulting directly or indirectly from
accessing any of the attached files which may contain a virus or the like. 


More information about the thelist mailing list