Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should you use the <label> tag and 'for' attribute?

Tags:

html

forms

seo

You can label an input field with a <label> tag like this:

<label for="username">Username:</label>
<input id="username" name="username" type="text">

But why?

Is it effective for SEO? Or browser rendering? Or better support for mobile or other devices?

like image 628
Andreas Furster Avatar asked Jul 09 '14 11:07

Andreas Furster


2 Answers

The label tag supports with a click the focus on the input element where id attribute equals labels for attribute. If you have e.g. a checkbox you can choose this one also with a click on the label.

Example:

<input type="checkbox" value="1" id="myCheckbox"/>

// A click here set the focus on the according checkbox without javascript things 
// And it's easier to select than a small checkbox element 
<label for="myCheckbox">My Checkbox</label>  
like image 184
Bernhard Avatar answered Sep 23 '22 00:09

Bernhard


The primary benefits are:

  • Accessibility - it lets screen readers know which form control the text applies to, this lets them accurately tell the user what they are expected to enter in a field
  • Click targets - clicking on the label has the same effect as clicking on the form control, larger click targets are easier to hit, especially when the input is as small as a radio button
like image 42
Quentin Avatar answered Sep 24 '22 00:09

Quentin