Some time ago, I’ve stumbled upon some specifications about the proper use of the label tag on webpages. And it seems that labels are a must if you want to make your page accessible to people with disabilities or if you just want to pass the Cynthia says validation and brag about it.

Proper use of labels

You can assign labels to text inputs or textareas by specifying the “for” attribute. Like so:

<label for="username">Enter your username</label>
<input type="text" name="username" id="username">

This will help screen readers and other software designed to help impaired people surf the web to correctly interpret your code and make the right associations between labels and textfields. For instance, the following piece of code displays a table row with some form tags in it:

<tr>
	<td>
		Enter your username
	</td>
	<td>
		<input type="text" name="username" id="username" />
	</td>
</tr>

For a normal visitor, this is very simple to understand because the “Enter your username” text and the username textfield are on the same line. But for a blind person that uses a screen reader, this will not be displayed at all. And the screen reader must decide witch text goes with what textfield.

On this example, I believe that most screen readers will make the right connection between text and textfield, but if the html code becomes a little more complicated (ie. more text or other tags) I sure that the screen reader will fail to make the right assumptions. But the use of labels can fix that.

Label’s accesskey

If you want to give your forms a cool “web2.0 style” functionality, you can specify the accesskey attribute for your labels. For example you can do something like:

<label for="username" accesskey="u">Enter your <strong>u</strong>sername</label>
<input type="text" name="username" id="username" />

…and when the user presses CTRL/ALT + u (depending on the browser) he’ll be taken directly to that textfield. Pretty neat.