DEV Community

loading...

How to make elements behave like links without wrapping them in anchor tags

26th_edmund profile image Edmund πŸš€ Originally published at theninja.codes on ・2 min read

This question has existed in different forms around the internet; "how to turn a div into a clickable link", "how to make div behave like link" etc. The most obvious way would be to wrap everything between a pair of anchor tags like this:

<a href="//google.com">
  <div>
    <p> Remaining elements here </p>
  </div>
</a>

Now this would work, assuming you're targeting only modern browsers that have support for HTML 5, because the HTML 4 specs did not approve of this. It would not work in older browsers because in HTML 4, inline elements can not be parents to block elements.

Another technique would have been to use an onclick listener attribute on the block element, but that's an accessibility no no.

So how do you make a div or any other block element behave like a link?(without surrounding them with an anchor tag of course)

short answer: with the help of CSS.

Long answer: keep reading please.

Using CSS to make div and other block elements behave like links

With the help of CSS positioning, we'll make the the link cover the entire area of the div whilst retaining it's structure in the DOM.

Take a look at the code sample below:

<div class="outer-element">
  <h2> The title to an article</h2>
  <p> The description to the article</p>
  <a href="path-to-article" class="link">link to article</a>
</div>

By setting the position of .outer-element to relative and .link to absolute with a few other CSS properties, we're able to make the anchor element cover the entire div without the text content of the link being visible:

.outer-element{
  width: 500px;
  height: 600px;
  box-shadow: 0px 0px 10px 1px #f1f1f1;
  position: relative;
}

.link{
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  text-decoration: none;
  z-index: 10;
  opacity: 0;
}

if you test the code snippets above, you should see that the link doesn't appear visibly but when you click the box you get redirected to the new destination.

Discussion (4)

pic
Editor guide
Collapse
devloco profile image
devloco

Don’t forget:
cursor: pointer;

Collapse
joeattardi profile image
Joe Attardi

You wouldn't need that because the <a> tag covers the whole div, and <a> tags automatically get the pointer cursor.

Collapse
joeattardi profile image
Joe Attardi

I don't know, this feels like a hack to me.

Collapse
26th_edmund profile image
Edmund πŸš€ Author

Haha I get what you mean Joe, the idea is to ensure that the elements retain the correct structure in the DOM.