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> </div> </div>
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:
h1not allowed as child of element
spanin this context.
Well then, what about the <a> element? With it it turns out there is no problem:
<a href="#"> <div class="test"> <h2>Something</h2> </div> </a>
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