Should I put input elements inside a label element?

前端 未结 14 1818
长情又很酷
长情又很酷 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 08:03

    The primary advantage of placing input inside of label is typing efficiency for humans and byte storage for computers.

    @Znarkus said in his comment to the OP,

    One of the big pros of putting the inside the , is that you can omit for and id: in your example. So much nicer!

    Note: In @Znarknus code, another efficiency was included not explicitly stated in the comment. type="text" can also be omitted and input will render a text box by default.

    A side by side comparison of keystrokes and bytes[1].

    31 keystrokes, 31 bytes

    
    

    58 keystrokes, 58 bytes

    
    

    Otherwise, the snippets are visually equal and they offer the same level of user accessibility. A user can click or tap the label to place the cursor in the text box.

    [1] Text files (.txt) created in Notepad on Windows, bytes from Windows File Explorer properties

提交回复
热议问题