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

后端 未结 8 1094
一生所求
一生所求 2020-12-02 16:26

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

Example of \"for\" attribute:



        
相关标签:
8条回答
  • 2020-12-02 17:03

    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.

    0 讨论(0)
  • 2020-12-02 17:05

    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.

    0 讨论(0)
  • 2020-12-02 17:07

    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.

    0 讨论(0)
  • 2020-12-02 17:10

    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.

    0 讨论(0)
  • 2020-12-02 17:18

    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.

    0 讨论(0)
  • 2020-12-02 17:19

    It doesn't matter. Both accomplish the same things in terms of defining the relationship between the label and field.

    0 讨论(0)
提交回复
热议问题