Is header in legend valid?

Caption

前端 未结 7 1182
萌比男神i
萌比男神i 2021-01-17 21:20

I use this in visual studio but the compiler claimed that h1 cannot be nested in legend element, but browser can render it anyway so i am confused

相关标签:
7条回答
  • 2021-01-17 21:27

    In HTML 5.2, this seems to be valid:

    4.10.16. The legend element Content model: Phrasing content and headings (h1-h6 elements).

    https://w3c.github.io/html/sec-forms.html#the-legend-element

    This is very good news, as in complex forms, legends serve the same purpose as headings do, and e.g. screenreaders only announce legends when focusing a form element.

    0 讨论(0)
  • 2021-01-17 21:39

    In HTML5 elements allowed inside <legend> elements are those in the Phrasing Content group. Per the docs:

    Phrasing content is the text of the document, as well as elements that mark up that text at the intra-paragraph level.

    0 讨论(0)
  • 2021-01-17 21:43

    if you check the html standards it says:

    <!ELEMENT LEGEND - - (%inline;)*       -- fieldset legend -->
    

    The %inline part means that it should only contain character level elements and text strings. So while it does render, you should not use it this way because the html is actually not valid.

    0 讨论(0)
  • 2021-01-17 21:44

    There are many things that browsers do that aren't required by the standards :-)

    This page here (HTML4) specifies the legend keyword and states that it can contain inline elements, of which the headers are not a part. It does have other possibly useful ones such as big or strong.

    In addition, the relevant page for H1 does not list legend as one of the items it's allowed to be contained within. You may also be able to use the id, class or style attributes of the legend to set the underlying textual properties.

    0 讨论(0)
  • 2021-01-17 21:46

    In HTML5, you can use an <h1> for the same purpose a legend serves in a fieldset, since a fieldset is considered a sectioning root. So if you want to be free from the legend's wonky styling quirks, use this accessible markup:

    <fieldset role="group" aria-labelledby="heading">
        <h1 id="heading">Caption</h1>
        <p>Other stuff...</p>
    </fieldset>
    
    0 讨论(0)
  • 2021-01-17 21:51

    The legend element of the fieldset is not designed to allow child elements unless they are considered "phrasing content". While most browsers will not complain (thus making it valid in pratice) you would probably be better off using a style to set the look/feel of your legend element as that is what css is for, elements should be used for logically grouping/identifing content not styling it.

    Legend: http://www.w3.org/TR/html5/forms.html#the-legend-element

    Phrasing Content: http://www.w3.org/TR/html5/content-models.html#phrasing-content

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