103

What is the correct code to create a link with heading 1 according to web standards?

is it

<h1><a href="http://stackoverflow.com"> stackoverflow </a></h1>

or

<a href="http://stackoverflow.com"><h1> stackoverflow </h1></a>

Thanks

Darko
  • 38,310
  • 15
  • 80
  • 107
ahmed
  • 14,316
  • 30
  • 94
  • 127

4 Answers4

159

According to web standards you aren't allowed to put block elements into inline elements.

As h1 is a block element and a is an inline element the correct way is:

<h1><a href="#">This is a title</a></h1>

Here is a link so you can learn more: w3 Visual formatting model

However, there is an exception that in HTML5 it is valid to wrap block-level elements (like div, p or h*) in anchor tags. Wrapping block-level elements in inline elements other than anchors still goes against the standards.

Darko
  • 38,310
  • 15
  • 80
  • 107
  • 21
    In HTLM5 this has changed. Both examples will validate - http://validator.w3.org/. – Atadj May 28 '13 at 16:06
  • nice one. its an easy mistake to make, and while both will validate its logical that naturally inline elements should be descendants of block level elements. – bigmadwolf Sep 23 '14 at 10:07
  • @pushplaybang - I would say it's more semantic to wrap the header in a link unless only part of the header is supposed to be clickable (I can't think of a use-case for that). Regardless, it's nice both are supported in html5. – aaaaaa May 01 '17 at 17:34
51

HTML5 updates this subject: it is now OK to wrap block-level elements with A's, as stated under another question: https://stackoverflow.com/a/9782054/674965 and here: http://davidwalsh.name/html5-elements-links

Community
  • 1
  • 1
f055
  • 1,190
  • 12
  • 23
7

a > h1 will cause difficulty in selecting text

Text Selection Issues

Since both are completely valid in HTML5, it is better to use h1 > a

2

As far as I understand HTML5 does allow you to wrap block level elements in link tags. However, bugs may show up in older browsers. I encountered this with Firefox 3.6.18 and got moz-rs-heading="" inserted into my code. Thus my styles broke. If you care about a work around, you can then wrap the link tags in divs. The following provides a better explanation of why the additional code works http://oli.jp/2009/html5-block-level-links/

Kip Deeds
  • 53
  • 6