Nested Anchor Tag Jun 28th 2020 Words: 367

Goal

Here’s a html card component

Click anywhere on the card will navigate user to the article, but urls in the abstract is also clickable and have their own href, asif the inner anchor is floating above the anchor wrapping the whole card.

Problem

When trying to construct a component like the following image, one problem we are facing is anchor tag cannot be nested in html. That’s to say, if we write the code as the one shows below, it does not work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<body>
<a href="#" class="card-anchor" onclick="alert('Outer anchor clicked');">
<div class="card">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Phasellus non nunc sed quam ullamcorper accumsan a ut justo.
<a href="#" onclick="alert('Inner anchor clicked');">I am clickable!!!</a>
Integer sed sodales eros, sit amet ultrices felis.
</p>
</div>
</a>
</body>
</html>

Workaround

Instead of wrapping the card with anchor tag, the anchor can be a child with absolute position, with css to positioning it as a cover.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<body>
<div class="card">
<a href="#" class="card-anchor" onclick="alert('Outer anchor clicked');"></a>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Phasellus non nunc sed quam ullamcorper accumsan a ut justo.
<a href="#" onclick="alert('Inner anchor clicked');">I am clickable!!!</a>
Integer sed sodales eros, sit amet ultrices felis.
</p>
</div>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.card {
position: relative;
}

.card > .card-anchor {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: 0;
}

.card a {
z-index: 1;
position: relative;
}

The position of the card should be relative in order for its children’s absolute position to work.