Always use the form Label tag

Late last year, a co-worker asked me why we weren’t using the <label> HTML form tag. I wasn’t sure, but it’s my job to know things like that. A little research revealed the answer: because I suck. From that point on, we’ve used the label tag wherever appropriate (some historical work hasn’t yet been updated, but it will be eventually).

If you ever find yourself writing (x)HTML forms, you should always use the label tag. In case you aren’t familiar with it (I thought I knew all there was to know about HTML, and I hadn’t even heard of it), here’s an example (try clicking on the text labels):

<div><input type=”radio” name=”options” id=”option1″ />
<label for=”option1″>Apples</label></div>
<div><input type=”radio” name=”options” id=”option2″ />
<label for=”option2″>Oranges</label></div>
<div><input type=”radio” name=”options” id=”option3″ />
<label for=”option3″>Papaya</label></div>

The label and corresponding input don’t have to be adjacent – they are associated with the for/id attributes. The label is then clickable just like the control and the browser does all the work for you – no messy JavaScript required.

It works in most every browser on the planet and the few that don’t support it (Safari being the most notable) ignore it gracefully. There are accessibility benefits and we all get clickable form labels that mirror the functionality of most operating system controls.

This tag has been around forever and smarter people than myself have been urging us all to use it for a long time. Since I was so late to the game, I thought I’d share, in case others like myself weren’t in the know.


7 thoughts on “Always use the form Label tag

  1. Thanks for sharing! I can’t believe there was such a useful tag that I didn’t even know about.

  2. Yes, nice tip, Steven. Neither was I aware of that one. It’s hardly surprising one could miss this kind of thing. Best to be aware that many sources of specifications are not 100% complete. Even so, when reading over specs it can be easy to overlook poorly-illuminated sections, especially when hurried (should sound familiar).

  3. Here’s another cool tip, which can improve discoverability for form labels. In your stylesheet, add the following line:

    label { cursor: pointer; }

    Using label:hover effects can serve a similar purpose.

  4. Be wary when adding styles directly to the label tag. Some browsers (I think Netscape in particular) get very, very unhappy when you do that, and will not render some elements on the page at all.

  5. This sucks! The click on the label works nicely but I can’t change the caption from javascript or at least I don’t know how to do it.

  6. Didn’t know that labels were clickable too! A bit disappointed that w3schools don’t explain the use of labels much at all… Thanks for sharing! 🙂

Comments are closed.