Align form elements using CSS (part II)
Should we use tables OR some other markup combining with CSS to lay out forms? Most of the people would say that forms are just interactive tabular data, so using table for laying out them is the idle option. A form has labels & controls just like the name -value pairs as table. You can use table to represent a form’s label-control pairs as the following:
<form>
<table>
<tr>
<th>Name</th>
<td><input type="text"></td>
</tr>
<tr>
<th>Address</th>
<td><input type="text"></td>
</tr>
</table>
</form>
This surely justifiably represent these name-value pairs, the label & the control lays in the same row & the <th> tags indicating the label of the row. But this pattern surely will not work if we want our labels to sit on top of our controls, for that, we have to split our name-value pairs in 2 different rows. Tables just dont give us enough flexibility of laying out forms justifiably.
We so can use <float>, <span> & <div> markups with CSS, something which I tried before. But still It does not feel good as there is more code involved. Clagnut has shown another alternative approach for laying out form in his blog & that is using the definition list tag.
<dl>
<dt>Name:</dt>
<dd><input type="text" name="name" /></dd>
<dt>Password:</dt>
<dd><input type="text" name="password" /></dd>
</dl>
Here the ‘labels’ are placed inside the <dt> (definition term) tags & the ‘form elements’ are placed inside the <dd> (definition definition) tags.
For side by side layout we can apply some simple styles:
form dt {
clear:both;
width:33%;
float:left;
text-align:right;
}
form dd {
float:left;
width:66%;
margin:0 0 0.5em 0.25em;
}
To layout form elements & their labels vertically, the style may be like the following:
form dt {
margin:0.5em 0 0.25em 0 ;
}
form dd {
margin:0 0 0 -0.25em ;
}
Using <dl> seems to better than using <span> or <div> tags as it is more flexible & lighter and at the same time also semantically correct. But still someone may argue that tables are more structurally meaningful & more flexible due to <tr> tag & “colspan” attribute & hence table should be used for laying out forms.
About this entry
You’re currently reading “Align form elements using CSS (part II),” an entry on anupom.toString( );
- Published:
- October 7, 2006 / 9:06 pm
- Category:
- HTML/CSS
- Tags:
5 Comments
Jump to comment form | comments rss [?] | trackback uri [?]