Should I put input elements inside a label element?

前端 未结 14 2070
长情又很酷
长情又很酷 2020-11-22 07:24

Is there a best practice concerning the nesting of label and input HTML elements?

classic way:



        
14条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 07:48

    A notable 'gotcha' dictates that you should never include more than one input element inside of a

    
    

    While this may be tempting for form features in which a custom text value is secondary to a radio button or checkbox, the click-focus functionality of the label element will immediately throw focus to the element whose id is explicitly defined in its 'for' attribute, making it nearly impossible for the user to click into the contained text field to enter a value.

    Personally, I try to avoid label elements with input children. It seems semantically improper for a label element to encompass more than the label itself. If you're nesting inputs in labels in order to achieve a certain aesthetic, you should be using CSS instead.

提交回复
热议问题