How to Properly Use HTML Input Elements with Label Elements in Forms

I still can't believe how many big-name websites neglect to use this wonderful bit of markup! Read this, and make it a habit. It's so easy!

Let's say we're marking up a contact form where visitors enter a bit of personal information, such as their name, sex, and which products they're interested in. I'll keep this stupid simple: when you're creating this form, there is a proper place to put the label for each input element. It's called the label element. Be sure to use the label element's for property, that way the label knows which input element it refers to.

The reason for going through this trouble rather than just using a <div> or a <span> element, is because the browser knows that if a <label> element with a for property is clicked that the corresponding input element should receive focus. Having the label AND the input element clickable makes for a much larger target to click on, making the human/computer interaction target more usable.

Here's an example, try clicking on the "Your Name" label and notice that the <input> will receive focus:

Source HTML: html <input id="name" type="text"/><label for="name">Your Name</label>

In this example, try clicking on the text label next to any of the checkboxes, radio buttons, or text fields. You will see that the appropriate input element is focused!

Our Example Form

Source HTML:

<fieldset style="border: 1px dashed #888; padding: 10px;">
  <legend>Our Example Form</legend>
    <input id="name" type="text"/>
    <label for="name">Your Name </label>
    <input id="gender-male" type="radio" name="gender" />
    <label for="gender-male">&nbsp;Male</label>
    <input id="gender-female" type="radio" name="gender" />
    <label for="gender-female">&nbsp;Female</label>
    <input id="web-development" type="checkbox" name="products" />
    <label for="web-development">&nbsp;Web Development</label>
    <input id="graphic-design" type="checkbox" name="products" />
    <label for="graphic-design">&nbsp;Graphic Design</label>
    <input id="video-editing" type="checkbox" name="products" />
    <label for="video-editing">&nbsp;Video Editing</label>
    <input id="logo-design" type="checkbox" name="products" />
    <label for="logo-design">&nbsp;Logo Design</label>

Have you used this technique, or something similar to help improve usability on your websites?  Tell me about it in the comments!

← Back to Overview