Thursday, March 3, 2011

The Standard For Linking <h> Tag Elements

Is either:

<a href="#"><h1>text here</h1></a>

or

<h1><a href="#">text here</a></h1>

"correct". Is there any benefit of using the first one, it seems more logical to me. Perhaps from an SEO point?

From stackoverflow
  • <h1><a href="#">text here</a></h1>
    

    is correct, as HTML does not allow a block element (<h1>) within an inline element (<a>) (src). your first example will fail validation.

    Generally, block-level elements may contain inline elements and other block-level elements. Generally, inline elements may contain only data and other inline elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.

  • Your second example is the only allowed structure. The first puts a block-level element inside an inline element and HTML does not allow this. Browsers may allow it, but it is not valid HTML.

  • There ain't really much difference in this particular case. There are some things to point out though:

    • <h*> are block elements, <a> is an inline element by default. As others pointed out, XHTML does not allow block elements in inline elements, so if you did not redefine their display style in CSS, <a><h1></h1></a> is invalid.
    • <a href="#"><h1>text here</h1></a> is a link that can have multiple child nodes. In this case, it only has a <h1> child node, but nothing is stopping you from adding more.
    • On the other hand, <h1><a href="#">text here</a></h1> is a header that can cave multiple nodes. You can add all sorts of child nodes to it, like labels, etc.

    So this is basically a logical difference without any practical differences in this particular case.

  • Additional note, although the former case works, its purely due to browsers being permissive. You may find via inspecting the internal dom tree that

     <a><h1>foo</h1></a>
    

    gets broken into

     <a></a>
     <h1><a>foo</a></h1>
     <a></a>
    

    And this can create interesting results. ;)

0 comments:

Post a Comment