HTML5 allows the use of block elements inside the
a tag, which was not permitted in HTML4. This means that you can wrap a link around whole sections of markup, making all of the child elements of the
a become the link. You use it like so:
<a href="http://example.com"> <div> <h3>I'm an example</h3> </div> </a>
You can begin to use this straight away, as every browser supports it — although you must be wary of one rather glaring bug in Internet Explorer.
The bug occurs if you try to nest other
a elements inside the block‐level one, as shown in this example markup:
<a href="http://example.com"> <div> <h3><a href="http://example.com">I'm an example</a></h3> </div> </a>
With this markup IE7 fails to render some elements, and IE8 and IE9 create an empty, ‘phantom’ element. I’ll show you what I mean, starting with the way this markup should render; on the left is the HTML markup as it displays in your browser, and on the right I’ve placed a screenshot from Firefox to act as a comparison.
And now see how they appear in IE7 (left) and IE8 & IE9 (right):
As you can see, in IE7 the
h3 element loses its background color and margin, and in IE8 & IE9 there’s an empty box above my markup; this is the ‘phantom’ element, which is inheriting the border from the
div element, and the
margin‐bottom from the
h3. Were I to add
margin‐top (or further properties that affect the box model) to my markup, they would also show up here.
Strangely, this bug doesn’t seem to occur in IE6.
The fix is quite simple: don’t nest
a elements. I only did it as I needed an element to create a particular style effect, but it can be done just as easily with a
span. I tried a number of other approaches but this seemed to be the only one that worked.
Update: As has been pointed out in the comments, nesting
a elements is in fact prohibited by the HTML5 specification. I’ll leave this post here for the other people like me who weren’t aware of that.