htmllabel

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


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>

Solution

  • 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.