Can a label only refer to input elements?

后端 未结 4 1254
有刺的猬
有刺的猬 2021-02-13 11:16

W3Schools have this to say about labels:

The tag defines a label for an input element. [Emphasis mine]<

相关标签:
4条回答
  • 2021-02-13 11:38

    According to the W3C it applies to Form Controls, and Form Controls are defined as:

    • Buttons
    • Checkboxes
    • Radio buttons
    • Menus
    • Text input
    • File select
    • Hidden controls
    • Object tags

    So FireFox is technically right, although I'd hardly consider it to be "breaking" if a browser didn't restrict it to those elements.

    0 讨论(0)
  • 2021-02-13 11:44

    I would say it was not an appropriate use of the markup, because label semantics are that they are specifically for controls.

    The LABEL element is used to specify labels for controls that do not have implicit labels,

    http://www.w3.org/TR/html401/interact/forms.html#h-17.9.1

    0 讨论(0)
  • 2021-02-13 11:56

    The latest WhatWG spec has this to say:

    Some elements, not all of them form-associated, are categorized as labelable elements. These are elements that can be associated with a label element.

    • button, input (if the type attribute is not in the Hidden state), meter, output, progress, select, textarea

    ...

    The for attribute may be specified to indicate a form control with which the caption is to be associated. If the attribute is specified, the attribute's value must be the ID of a labelable element in the same tree as the label element.

    (Source: https://html.spec.whatwg.org/multipage/forms.html.)

    In other words, the standard only allows for attributes to point at elements of one of the 7 tag types listed above. The HTML exhibited in the question (which uses a for element to point to an editable div) is therefore technically invalid HTML under the current spec.

    The Nu Html Checker (which is endorsed by WhatWG) agrees; if you ask it to validate the HTML document from the question, it will say:

    Error: The value of the for attribute of the label element must be the ID of a non-hidden form control.

    0 讨论(0)
  • 2021-02-13 12:02

    The HTML spec says, about label's "for" attribute, "When present, the value of this attribute must be the same as the value of the id attribute of some other control in the same document. When absent, the label being defined is associated with the element's contents."

    So the id references in "for" should be that of a control. What's a control? The spec basically says any input is a control, as is button, select, or object. So Firefox is technically right -- a div is not a control.

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