Semantically, which is more correct: a in h2, or h2 in a?
Solution 1:
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.
Solution 2:
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)
Solution 3:
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:
Phrasing content is the text of the document, as well as elements that mark up that text at the intra-paragraph level. Runs of phrasing content form paragraphs.
and in the following list you have that phrasing content include:
a (if it contains only phrasing content)
So, if the a
tag includes only phrasing content, HTML5 allows it to be contained within a h2
tag.
Viceversa, the text level semantics page describes the a
element content model as follows:
Transparent, but there must be no interactive content descendant.
Following the Transparent link, at the end of the description is found the following:
When a transparent element has no parent, then the part of its content model that is "transparent" must instead be treated as accepting any flow content.
Since in the h2
tag description it is said:
Contexts in which this element may be used: Where flow content is expected.
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.
Solution 4:
HTML allows things inside <a>
tags
I have this...
<header>
<a href="/home">
<h1>Main heading</h1>
<h2>Sub heading</h2>
</a>
</header>
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.