Should I put input elements inside a label element?

前端 未结 14 1982
长情又很酷
长情又很酷 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:55

    Behavior difference: clicking in the space between label and input

    If you click on the space between the label and the input it activates the input only if the label contains the input.

    This makes sense since in this case the space is just another character of the label.

    Inside:

    Outside:

    Being able to click between label and box means that it is:

    • easier to click
    • less clear where things start and end

    Bootstrap checkbox v3.3 examples use the input inside: http://getbootstrap.com/css/#forms Might be wise to follow them. But they changed their minds in v4.0 https://getbootstrap.com/docs/4.0/components/forms/#checkboxes-and-radios so I don't know what is wise anymore:

    Checkboxes and radios use are built to support HTML-based form validation and provide concise, accessible labels. As such, our s and s are sibling elements as opposed to an within a . This is slightly more verbose as you must specify id and for attributes to relate the and .

    UX question that discusses this point in detail: https://ux.stackexchange.com/questions/23552/should-the-space-between-the-checkbox-and-label-be-clickable

提交回复
热议问题