Should you wrap block elements with anchor tags?

Kid hugging a dog. Kid represents tag and dog the tag

A question that pops every now and then — should you wrap block elements with anchor: <div> with anchor tag <a> ? This is one of the many decisions front-end developers have to make on a daily basis.

TLDR: Yes, you can. Don’t sweat over it.

First – what is the difference between a block and an inline element like <a>?

By default, a block-level element occupies the entire space of its parent element (container), thereby creating a “block.” 

Block-Level Elements, MDN

In the general case, we wrap content or inline elements with block ones. Of course, all these examples take into consideration the default state, not the custom styled one from css. Take this example:

<div class="parent">
	<div class="child">
		<p>All three tags are block level ones.</p>

And of course, we can add inline HTML elements inside block ones:

<h1>Hello there, <span class="name">Jake</span></h1>

But, how about wrapping an inline element like <span> or <a> around a block level one like <div>?

If we wrap <span> around <h1>, we get an validation error:

Element h1 not allowed as child of element span in this context.

HTML Validator

Well then, what about the <a> element? With it it turns out there is no problem:

<a href="#">
	<div class="test">

Document checking completed. No errors or warnings to show.

HTML Validator

One thing that is worth mentioning though is that this is only valid for HTML5, but… do we really consider this nowadays? So yes, in the end, you can wrap block elements with anchor.

Also, considering styling, make sure that you check if everything is working correctly for you. Most likely, a display: block to the <a> element would clear out some inconsistencies in the layout.

And if I can add one final note — try not to achieve such results with JS because HTML might seem messy. First research if it is really an invalid code, if it’s not supported and if there is another way to achieve what you go for. Only then, if there are no options go for a JS approach. Consider it last resort

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.