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:
In HTML it might be written as this:
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 🧙
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 :)