Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to wrap the label tag around a form item or use the "for" attribute in HTML?

Tags:

html

label

I know that you can use both but is it better to use one over the other? If so, why?

Example of "for" attribute:

<input type="text" id="male"><label for="male">Male</label> 

Example of wrap:

<label>Age:<input type="text"></label> 
like image 631
James Gardiner Avatar asked Aug 16 '12 16:08

James Gardiner


People also ask

Should you wrap input in label?

There are two ways to pair a label and an input. One is by wrapping the input in a label (implicit), and the other is by adding a for attribute to the label and an id to the input (explicit). Think of an implicit label as hugging an input, and an explicit label as standing next to an input and holding its hand.

Why should the value of the for attribute of label tag be same as the ID of the corresponding input element?

A label is attached to a specific form control through the use of the for attribute. The value of the for attribute must be the same as the value of the id attribute of the form control. The id attribute may have the same value as the name attribute, but both must be provided, and the id must be unique in the Web page.

Why do we use attribute in label tag?

The for attribute is an allowed attribute for <label> and <output> . When used on a <label> element it indicates the form element that this label describes. When used on an <output> element it allows for an explicit relationship between the elements that represent values which are used in the output.

What is the advantage of associating a label with an input element?

Associating a <label> with an <input> element offers some major advantages: The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too.


2 Answers

Semantically, both possibilities are the same. But depending on what layout you want, there are advantages and disadvantages for the two possibilites. For example, if you want that the label is at an entirely different place, it would not make any sense to put the input into the label. But if you want to be able to make a hover-effect via css, that sets e. g. a background for both the label and the area around the input, it would be better to put the input into the label.

like image 82
matthias.p Avatar answered Sep 30 '22 21:09

matthias.p


according to http://www.w3.org/TR/2008/WD-WCAG20-TECHS-20080430/H44.html

some assistive technologies do not correctly handle implicit labels

So when you wrap, you may also want to provide the "for" attribute to the label element.

like image 26
raycohen Avatar answered Sep 30 '22 19:09

raycohen