HTML - Correct way of coding a checkbox with a Label

后端 未结 3 2014
北荒
北荒 2021-01-04 10:29

I\'ve been using formtastic in order to generate HTML forms on rails applications. My question, however, is really HTML-related.

Today I found a strange behaviour on

相关标签:
3条回答
  • 2021-01-04 10:57

    In addition to the reasons mentioned in the other answers, if the <label> and <input> are separate any whitespace between them will be non-clickable. This probably isn't what you wanted. For example, the newline in this code will result in a non-clickable gap:

    <input id="my_boolean_field" type="checkbox" ... >    
    <label for="my_boolean_field">This is my boolean field</label>
    

    Nesting the <input> inside the <label> avoids this, because the whitespace is part of the label.

    Live example: http://jsfiddle.net/xKLrS/2/

    0 讨论(0)
  • 2021-01-04 11:01

    Can anyone tell me why enclosing checkboxes inside their <label> tag might be a good idea

    It might be a good idea because you could lose the id and for attributes in this case, making the markup simpler. When an <input> is inside a <label>, the connection between them is implicit. (See HTML4 section 17.9.1.)

    However, in practice this doesn't work in IE, so you lose that potential advantage.

    I can only assume in this case it's for layout/styling reasons.

    0 讨论(0)
  • 2021-01-04 11:09

    The common UI for a text input is either a label on the left:

    Email address: [____________________]
    

    Or the label above the input:

    Email address:
    [___________________________________]
    

    For a checkbox however, the common UI is for the label to appear after the input, like this:

    [x] Accept terms and conditions
    

    For the first two cases, it drastically simplifies the CSS you have to create if the label comes before the input in the markup. One could argue that the label could wrap around the input still, but the important thing here is that the text comes before the input.

    In the third example (the checkbox), the text comes after the label, and again, the CSS is greatly simplified by putting the label in the right place in the markup order (after the input).

    So, the checkboxes were always going to be different to the rest of the inputs. In regards to the wrapping of the checkbox with a label, this was just a personal preference, although I'd argue that since the checkbox inputs are different, having the input inside the label makes it easier to target these inputs for styling with CSS, because the markup is different.

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