CSS Tip: Using a Nested Link to Fill an Entire Div

Hyperlinks are a big part of every webpage, even if they’re not completely apparent. Typically you’d only have text or maybe wrap a <button> element with a link. Sometimes, a design called for an entire <div> (or any other sectional element) to be a clickable link. A typical example is an entire block with some text and an image to be clickable from all around.

Another example is an entire block that contains a link to an article:

This is a block from my /blog page. The entire ‘read post’ element is clickable. With this technique, it would be possible to make the entire <article> clickable as well.

Here’s an example:

<article>
    <div class="head">
        ...
    </div>

    <div class="body">
        ...
    </div>
</article>

One approach is to wrap the entire div with a link tag, but that approach can trickle down styles to the nested text elements that you may not want. The semantic implications can also be troublesome if you’d rather convey that this is an <article> and not an <a>.

How can we have a nested <a> tag take up the whole div without wrapping it? It’s actually not too hard.

<article>
    <a class="absolute-link" href="#"></a>
    <div class="head">
        ...
    </div>

    <div class="body">
        ...
    </div>
</article>

Note: You can add the link anywhere as long as it’s nested one level under the parent you want to fill.

The CSS is pretty straightforward. It requires one chunk of code and making the parent position: relative. Here’s an example.

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

article.article-class {
    position: relative;

    .absolute-link {
        @extend %absolute-link;
    } 
  }
}

As you see, all it does is expand the entire width/height and take precedence with z-index. Hope it helps!

Leave a Comment