Anne van Kesteren

The element label

There are a couple of HTML elements, which should be used a lot more. Actually, they should always be used. They don't break your layout in older browsers, but add extra usability and accessibility to the newer ones. Those newer browsers, like Mozilla, Netscape (not Netscape Navigator 4.x!), IE5.x & IE6 all support this. The first element I'd like to know you about is label. label is always used in forms (this is not label from XHTML 2). The element label I'm talking about comes from HTML 4.

It has one important attribute: for, which is an IDREF. The id where it points to is inside a form element, like input. A simple example:

<form action="" method="post">
 <p>
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" />
 </p>
 <p>
  <input type="submit" value="Send" />
 </p>
</form>

If you click on "Name:" the input element where the label element points to gets focus. This is especially useful with checkboxes and radio buttons, who are pretty small and difficult to hit. The following is also possible with this element:

<form action="" method="post">
 <p>
  What color do you like?
 </p>
 <p>
  <label>Green <input type="radio" name="color" value="g" /></label>
  <label>Red <input type="radio" name="color" value="r" /></label>
  <label>Yellow <input type="radio" name="color" value="y" /></label>
 </p>
</form>

I just noticed this doesn't work in IE, so you have to use the previous one. As a bonus I'll give you a tip to style these things:

label{
 display:block; /* the input element will be aligned under the label element */
 cursor:pointer; /* makes it clear that you can click on it, if you want to support IE5 use cursor:pointer; cursor:hand;*/
}

That's it, other elements will follow (I hope).

Comments

  1. Yes, you are right, I should use this. But I think it could be made clearer why it is so important...

    Posted by Ben de Groot at