Blog-Archiv

Montag, 18. April 2016

What's HTML label for?

I saw this many times before I asked myself "Why do they do this?". I'm talking about the HTML-5 <label for="....."> tag.

    <label for="prologue">Prologue</label>
    <input type="checkbox" id="prologue"/>

The label tag is mostly used together with some input field. The label's for attribute points to the id of the input-field it labels. That means you need to create a page-globally unique id, and then write it into both the label and the input tag.

Isn't this much ado about nothing? Couldn't we simply use a span to label the field? Why use an expensive id when we must position the label before or after the input field anyway?

There are two things to say about this.

Label Forwards Clicks

The label will forward mouse clicks to the input field. That means, clicking the label is like clicking onto the input field.
A checkbox would toggle its value from a click onto its label. It wouldn't do this without the label-for.
A text field would show the editing cursor and be ready for receiving keyboard input, just from clicking onto its label.

Here is a something for trying out:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    
    <title>The "label" tag forwards click events</title>
  </head>
  
  <body>

    <label for="prologue">Prologue</label>
    <input type="checkbox" id="prologue"/>

    <label for="textarea">Text</label>
    <textarea id="textarea" cols="20" rows="6" style="vertical-align: top;"></textarea>
        
  </body>
</html>

After I had accepted the fact that label makes sense, I asked myself if it is worth. Needing to create an id on the input-field and referring to it in the label makes this somehow heavyweight. But fortunately there is a lightweight variant available.

Label can Enclose Input

Use this instead of the code above:

    <label>Prologue
      <input type="checkbox"/>
    </label>

    <br>

    <label>Text
      <textarea cols="20" rows="6" style="vertical-align: top;"></textarea>
    </label>

This does exactly the same.
Enclosing the input into the label tag makes the id dispensable.




Keine Kommentare: