I'm stuck deciding which to use as both seem to work.
Should I be placing links <a>
inside of <h2>
elements?
Or the other way around?
What is the correct standard?
I'm stuck deciding which to use as both seem to work.
Should I be placing links <a>
inside of <h2>
elements?
Or the other way around?
What is the correct standard?
Also its not functioning same, there is one big difference.
If you put
<h2>
into<a>
the whole block (for example line) of heading will work like link.However if you put
<a>
into<h2>
, only visible text will work as link. (you can test it with cursor change)HTML allows things inside
<a>
tagsI have this...
And it works for me.
The whole heading text including the subheading is clickable as I want. I don't know of a better way to do this with html 5.
The answer is that it depends...
From the W3C website, more specifically in the HTML5 semantics page, it is clear that h2 elements (as all other heading tags) have as content model "Phrasing content".
Now, following the Phrasing content link, you get the following description:
and in the following list you have that phrasing content include:
So, if the
a
tag includes only phrasing content, HTML5 allows it to be contained within ah2
tag.Viceversa, the text level semantics page describes the
a
element content model as follows:Following the Transparent link, at the end of the description is found the following:
Since in the
h2
tag description it is said:an
h2
tag may the considered as flow content.So, if the
a
tag has no parent, in HTML5 it must be treated as accepting any flow content, including h2 tags.You can only place
<h2>
elements within<a>
elements if you're working with HTML5, which allows any other elements within<a>
elements. Previous specifications (or current ones however you want to look at them) never allowed this.The usual way of doing this is to place
<a>
within<h2>
. This works, has always worked, and has been the only valid way to do it before HTML5, for heading links, as the link refers to the text in that heading. You rarely need to place<h2>
within<a>
unless that<h2>
is part of some more complex structure which functions as a hyperlink as a whole.<h2>
is block-level and<a>
is not, so<h2>
can contain<a>
but not the other way aroundhttp://htmlhelp.com/reference/html40/block.html
The W3C specs for h2 say that its permitted parent elements are anything that can contain flow elements, or hgroups. The specs for a permit parent elements that can contain phrasing or flow elements. h2 can contain phrasing content, and a can contain phrasing or flow content, so based on the spec it appears that either is permitted.
Since you included the semantics tag, I assume you're interested in which 'seems' better too. For my part, since I can't think of when I'd want an anchor to span a heading plus other content, but I can think of plenty of times when a header should contain an anchor plus other content, a inside h2 seems the best route to go.