Skip to content

Accessible nested links

Posted on:January 10, 2024

You have a clickable card or any clickable container element that contains interactive elements inside it. You want a click on the container itself will navigate to its full content but also allow clicking on other elements inside it.

You might just nest those a tags, but that will lead to an accessibility issue, which is a big no no.

Another option will be to programmatically navigate with some click handler in JavaScript which is again less optimal.

There is a way to overcome this problem with only CSS!

Consider the following component of a blog post:

Card with links

In HTML it might be written as this:

<div class="card">
<a href="/posts/accessible-nested-links" class="cta"
>Accessible nested links</a
>
<p>How to accessibly nest links, with only css</p>
<a href="/about">By Tom Slutsky</a>
</div>

This markup is completely fine accessibility-wise. However, the card itself is not clickable!

To make it clickable we are going to use some CSS sorcery 🧙

.card {
position: relative;
}
.card > a {
z-index: 1;
}
.cta::before {
content: "";
position: absolute;
width: 100%;
height: 100%;
}

And Viola!

We added a before to our main a tag (which we want the card click to trigger) and expanded it to cover the entire card. Therefore, clicking the card is the same as clicking the link.

We also added a z-index to all links inside the card so that they will rise above the card-covering link.

And that’s it! We kept our accessible markup, got the behavior we wanted and even keyboard navigation will work as expected as long as the main link it the first one in the card.



If you found it useful, I will be happy to hear about it :)