Explain Codes LogoExplain Codes Logo

Html - how to make an entire DIV a hyperlink?

html
responsive-design
accessibility
best-practices
Alex KataevbyAlex Kataev·Oct 11, 2024
TLDR

To swiftly convert your <div> into a clickable entity, simply envelope it in an <a> tag:

<a href="https://example.com" style="display: inline-block; text-decoration: none;"> <div style="color: black; border: 1px solid #ccc; padding: 10px;"> Click me hard, I'm a div </div> </a>

The display: inline-block; guarantees the <a> tag respects the dimensions of your <div>, while text-decoration: none; keeps your text unscathed.

Adapting to your needs

Stirring the JavaScript pot

When you're unable to wrap your <div> in an <a> tag (maybe it's Monday, things happen), resort to JavaScript:

<div onclick="window.location.href='https://example.com';" style="cursor: pointer;"> Clickable Div </div>

This configuration adds a direct link to https://example.com upon div click. Remember to set cursor to pointer (🖐️ is universal for "click me").

Making friends with screen readers

When accessibility matters, and it should, cater to screen readers with semantic HTML. Set an <a> tag around the <div> and stitch in some CSS to cover your bases:

<a href="https://example.com" style="display: block; width: 100%; height: 100%;"> <div> Where we're going, we don't need 'div' roads </div> </a>

Contingency plans are cool

For those living dangerously with JavaScript disabled, furnish a fallback mechanism. The <a> tag is your reliable companion, but noscript tag may come in handy for alternative display:

<noscript> <a href="https://example.com">Link for the wild ones</a> </noscript>

Dealing in CSS

Unlock CSS's hidden potential for a user-friendly experience. Play around with hover effects, background color changes, focus outlines for keyboard navigation, and maintain unaffected text elements:

div.link-like { border: 1px solid #ccc; padding: 10px; /* Like a comfy cushion */ } div.link-like:hover { background-color: lightblue; /* div's day at the beach */ } div.link-like:focus { border-color: blue; /* Bluer than a Smurf's backside */ }

SEO friendly, as friendly can be

When creating links, especially billboard-sized clickable areas, don't forget SEO-friendly practices. Use text that's descriptive and relevant to enhance your SEO scores.

New tab or not new tab

There are debates in the world of web design about whether links should open in a new tab. Using window.open within an onclick event entertains this debate:

document.getElementById('clickable-div').addEventListener('click', function() { window.open('https://example.com'); // The internet version of "find you in another tab" });

For peace, simply using location.href within the event does a great job.