Is putting a div inside an anchor ever correct?
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:
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:
'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.
Was this article helpful?