Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Nested Anchor Links using CSS

Have you ever encountered a situation where you have an area, let’s say a <div> element, which is a hyperlink and you wanted another hyperlink inside that <div> element which should also be clickable?

A possible use case would be a card component whose entire area is a hyperlink and you want to have another hyperlink inside that card which should also be clickable on its own.

This could look something like this.

nested hyperlink representation using card layout

The Problem

To be able to achieve something like this, your first line of thought would be to use a <div> tag inside the <a> tag. After that, you would nest the <a> tag in this setup further.

This would fail quickly because the <a> tag is not allowed to be nested inside another <a> tag. The browsers would try their best to fix it on their own and put the nested <a> tag outside the parent <a> tag when rendering the DOM.

Turned out, the solution to this is pretty simple that I learned from this video of Laracasts. So, all the credits for this tip goes to them.

The Solution

The trick to solving this problem is to set the position of the outer <div> (the card component in our case) to relative and then create an empty <a> tag inside the outer <div> and make the following adjustments to it.

  • Set its position to absolute.
  • Set inset to 0.

What this does is that it creates an empty <a> tag which is absolutely positioned inside the outer <div> and it has no content. Setting inset to 0 will make sure that the <a> tag takes up the entire space inside the outer <div>.

<div style="position: relative">
    <p> 
        Outer card content
        <a href="https://google.com" style="position: absolute; inset: 0;"></a>
    </p>
</div>

Now, to have another hyperlink (the nested card) inside the outer div, we can simply create another <a> tag inside the outer <div> and set its position to relative and inset to 0.

<div style="position: relative">
    <p> 
        Outer card content
        <a href="https://google.com" style="position: absolute; inset: 0;"></a>
    </p>

    <a href="https://amitmerchant.com" style="position: relative; inset: 0;">
        <div>
            <p>Inner card content</p>
        </div>
    </a>
</div>

And that’s about it! This setup will create an illusion of a nested hyperlink without sacrificing the clickability of the outer <a> tag.

Here’s a CodePen to demonstrate this.

See the Pen Box Without A Gradient Shadow by Amit Merchant (@amit_merchant) on CodePen.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?