Tableless CSS form layouts - Part 2
In part 1 we looked at creating a simple form using CSS for layout. Now we'll move on to something more complex.
In this part I will show you how to create forms that include mandatory fields, fieldsets, multiple checkboxes and radio buttons.
Multiple input boxes, one label
Let's start with something easy - an input field that has no label.
For example, when asking for an address, we often have a number of rows with just one label:
Oops, that isn't quite right. We need to get them all to align. The easiest thing to do is assign a class to the rows that have no labels:
p.labelless
{
margin-left: 145px;
}
<p>
<label for="address1">Address</label>
<span><input name="address1" id="address1" /></span>
</p>
<p class="labelless">
<span><input name="address2" id="address2" /></span>
</p>
<p class="labelless">
<span><input name="address3" id="address3" /></span>
</p>
This will appear correctly as:
Fieldsets
This is the perfect time to introduce fieldsets. Fieldsets should be used to group together form items in a logical way. All the address input fields should be in one fieldset. Each fieldset should have a legend but as it is almost impossible to style this in CSS I prefer to use a heading (h1, h2, h3) tag.
<fieldset>
<h3>Contact details</h3>
<p>
<label for="address1">Address</label>
<span><input name="address1" id="address1" /></span>
</p>
<p class="labelless">
<span><input name="address2" id="address2" /></span>
</p>
<p class="labelless">
<span><input name="address3" id="address3" /></span>
</p>
</fieldset>
This will look like this:
Checkboxes and radio buttons
We can use a similar approach to deal with radio buttons and checkboxes. First create a separate class for each row that differs from the standard combination. Here we will have .multiple for rows with multiple radio buttons and .checkbox for rows with the right hand column having a checkbox next to some text.
We want it to look like this:
Note how each row clears the one above regardless of which column is longer - that's what encasing each row in a paragraph tag did. This is the code:
<p class="multiple">
<label>Do you have permission to work in the UK?</label>
<span><input type="radio" id="yes" name="workPermit" value="yes" /> <label for="yes">Yes</label> <input type="radio" name="workPermit" id="no" value="no" /> <label for="no">No</label></span>
</p>
<p class="checkbox">
<label for="terms">I have read and understood the terms and conditions</label>
<input id="terms" type="checkbox" value="1" name="terms" />
</p>
And here are the styles:
.checkbox label
{
float: right;
width: 175px
}
.multiple span label
{
display: inline;
float: none
}
You can use these same principles to add other non-standard form items like upload fields or submit buttons. Good luck!
18 January 2007