I know that you can use both but is it better to use one over the other? If so, why?
Example of \"for\" attribute:
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.
If it counts for anything, frameworks like ASP.NET put the label
element next to the input
/select
/textarea
elements and use the label
's for
attribute.
The 'label for' syntax means the label you have created is intended to be a label for the input with id 'inp'. If you click this label in most browsers the cursor focus will land on the 'inp' input element. It's a nice little way of linking a label with its corresponding form control.
I'm not aware of compatibility issues, or any around performance. To me it seems syntactically sound, and as far as I'm aware the CSS spec claims that both are valid.
The wrap allows to drop the for
attribute, which in turn allows to omit the `id' attribute on the input element. Great for templates or any forms that need to be used in multiple instances on a page.
Embedding the input in the label also affects the wrapping behaviour. <label><checkbox/>Value with spaces</label>
will wrap as a single unit by default. Whereas <checkbox id="check"/><label for="check">Value with spaces</label>
will wrap the text with breaks at spaces and will wrap the label to a new line but leave the checkbox above.
It doesn't matter. Both accomplish the same things in terms of defining the relationship between the label and field.