How to Make a Div a Clickable Link

<div> elements are important in CSS-based web design as they give structure to HTML. Sometimes you may need to make the whole <div> element clickable as a link. To do this, you can find some methods in our snippet and choose the appropriate method for you.

Follow the given steps for the first solution. It's about making an anchor tag inside a div, and styling the anchor so it covers all the area inside the div

The first solution uses CSS absolution position, which is a bad practice most of the time. You can scroll down to see the other solution.

Create HTML

  • Create a <div> with a class name "container".
  • Use the <a> element to add the needed link.
<body>
  <div class="container">
    W3Docs
    <a href="https://www.w3docs.com/">
      <span class="link"></span>
    </a>
  </div>
</body>

Create CSS

  • Set the position to "absolute" for the inner <a> tag.
  • Use the z-index property to place the link above all the other elements in the div.
.container {
  font-size: 5em;
  background-color: #a8a8a8;
  color: white;
  width: 8em;
  height: 2em;
  line-height: 2;
  text-align: center;
  font-family: Helvetica, Arial, sans-serif;
  font-weight: bold;
  cursor: pointer;
  position: relative;
}

.link {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 1;
}

Let’s see the full code.

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      .container {
        font-size: 5em;
        background-color: #a8a8a8;
        color: white;
        width: 8em;
        height: 2em;
        line-height: 2;
        text-align: center;
        font-family: Helvetica, Arial, sans-serif;
        font-weight: bold;
        cursor: pointer;
        position: relative;
      }
      .link {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 1;
      }
    </style>
  </head>
  <body>
    <div class="container">
      W3Docs
      <a href="https://www.w3docs.com/">
        <span class="link"></span>
      </a>
    </div>
  </body>
</html>

Result

W3Docs

You can also use the <div> nested inside a hyperlink.

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      a {
        display: block;
        background: orange;
        padding: 20px;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <a href="https://www.w3docs.com/learn-html/html-introduction.html">
      <div>
        This is a clickable div.
      </div>
    </a>
  </body>
</html>
As the div takes place inside the anchor tag, the anchor tag covers all the div's area, and thus the div becomes a clickable link.