Explain Codes LogoExplain Codes Logo

Is putting a div inside an anchor ever correct?

html
responsive-design
best-practices
accessibility
Nikita BarsukovbyNikita Barsukov·Nov 1, 2024
TLDR

In HTML5, yes you can nest a div within an a element. This is a shift away from the previously strict rules of HTML. For this structure to work correctly, you want to ensure that the a element is set to display as block or inline-block and it wraps legitimate flow content. This activates your markup and keeps it logically accurate. For example:

<a href="https://example.com" style="display: block;"> <!-- Div at rest, anchor in motion --> <div>Clickable Content</div> <!-- Relax, I'm just a div inside an anchor. Absolutely normal in HTML5 --> </a>

The takeaway: Setting the block level display to a enables it to comfortably host a div, aligning perfectly with the more relaxed content model of HTML5.

Transparent content model in HTML5

The content model of <a> in HTML5 is termed as transparent. This means it can wrap almost any other content, excluding interactive elements like buttons or other <a> tags. So while casually placing a div inside your <a>, ensure to drop any elements that might clash with the parent anchor's functionality.

Document structure and accessibility

When embedding a div inside an a, document structure should be your priority. Organize your elements so they make sense even without CSS. This allows a clear and coherent document flow which enhances accessibility and SEO performance.

HTML4 support and cross-browser compatibility

To ensure cross-browser compatibility, particularly for older browsers that strictly adhere to HTML4, consider using a <span> tag styled to display: block instead of the <div>. This allows your code to pass the validation checks and offers wider compatibility:

<a href="https://example.com"> <!-- Hello from pre-HTML5 era --> <span style="display: block;">Clickable Content</span> <!-- Promise I'm just a span following HTML4 rules, not a rebellious div --> </a>

'Real-life' examples in professional libraries

Frameworks like Angular Material provide a bunch of practical cases of div inside an a, staying true to the HTML5 guidelines. So hit those docs and understand better how seasoned developers handle this.

Potential navigation issues

Including multiple focusable elements inside div may create "tabindex" conflicts which hamper user navigation. In order to ensure seamless navigation for all users, keep things uncomplicated inside clickable elements.

Denylist for contents within an anchor

Watch out! Interactive content like a button, input, or another <a> inside your anchor element is considered bad practice. They might lead to confusion and unexpected behavior.