CSS Forms Sample

by Brian DeMarzo

If you have questions, go to my blog site at http://www.sidesofmarch.com.

Form: Fieldset: Legend


Main layout created using ___layouts. Font sizes normalized using Yahoo's YUI Fonts CSS.

Instructions:

  • Include the CSS shown at the end of this document. A min-width is highly recommended, as is the appropriate IE 6 hacks.
  • Use a fieldset tag around your form elements.
  • The legend tag is optionat (but recommended).
  • Wrap each "row" in your form in a <div class="row">. Set any background colors on this class.
  • Wrap each label in a <div class="label">. Set the width to the label class as appropriate (25% in this example). Note that padding-top:0.1em in this class ensures the labels line up nicely with the fields.
  • Give labels of required fields the required class (bolds the label by default).
  • Wrap each form field in a <div class="field">. Set the width to 100% less the width of your div.label (75% in this example).
  • Put a <span class="related"> around the label and input tags of your check box and radio controls. This set white-space:nowrap, ensuring boxes stay with labels.
  • If you have a field for which you don't want a label on the left, add the class nolabel to its div tag. This will make it align with the left side of the fieldset.
  • If you have changed the font size (such as by specifying body { font-size:80%; }, you will need to adjust the size of radio controls and checkboxes. Failing to do this could result in labels being misaligned with the controls. Simply adjust the with and height of the input[type="radio"] and input[type="radio"] selectors to a size relative to the font size change. For example, specifying font-size:80%; would require a width and height of 0.8em.

The CSS

body
{
	margin:1% 2.5%;
	font-size:90%;
}
fieldset
{
	border-style:solid;
	border-color:#000000;
	border-width:1px;
	padding:0px;
	margin:1em 0px;
}
fieldset legend
{
	color:#FFFFFF;
	background-color:#000000;
	font-weight:bold;
	font-size:125%;
	padding:2px 4px;
	margin:0px 0.5em 0.2em 0.5em;
}
fieldset div.row
{
	background-color:#999999;
	margin:4px 0px;
	padding:0.2em 0.4em;
	clear:left;
	overflow:hidden;
}
fieldset div.row div.label
{
	float:left;
	width:25%;
	padding-top:0.1em;
}
fieldset div.row label.required
{
	font-weight:bold;
}
fieldset div.row div.field
{
	float:left;
	width:75%;
	overflow:hidden;
}
fieldset div.row div.nolabel
{
	float:none;
	position:relative;
	width:100%;
}
fieldset div.row div.field span.related
{
	white-space:nowrap;
}
fieldset div.row div.field input[type="radio"], fieldset div.row div.field input[type="checkbox"]
{
	width:0.9em;
	height:0.9em;
	vertical-align:top;
}

The following CSS should be for IE browsers only, using conditional comments (as done here) or some other hack.

<!--[if IE]>
<style type="text/css">
fieldset div.row div.field input[type="radio"], fieldset div.row div.field input[type="checkbox"]
{
	vertical-align:middle;
}
</style>
<![endif]-->