Is header in legend valid?

Caption

2019-02-21 19:45发布

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 that this is valid or not?

<fieldset>
   <legend>
     <h1>Caption</h1>
   </legend>
</fieldset>

7条回答
We Are One
2楼-- · 2019-02-21 20:30

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.

查看更多
趁早两清
3楼-- · 2019-02-21 20:33

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>
查看更多
来,给爷笑一个
4楼-- · 2019-02-21 20:38

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.

查看更多
倾城 Initia
5楼-- · 2019-02-21 20:45

no it is not valid inside the legend. you can use wc3 validator to validate your code

查看更多
一纸荒年 Trace。
6楼-- · 2019-02-21 20:45

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

查看更多
虎瘦雄心在
7楼-- · 2019-02-21 20:46

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.

查看更多
登录 后发表回答