Another way to achieve this is to make use of pseudo elements (::before
or ::after
) on the anchor.
- Starting off, the initial attempt might be something as follows:
a::after {
content: '';
display: block;
height: 100%;
width: 100%;
}
The above code block will create a pseudo element which will appear underneath the anchor.
- Then by setting a relative position on the table cells (
td
/th
) and absolute position on the anchor's pseudo element — which will now be positioned relatively to its table cell. This achieves two main things: i) take the pseudo element out of normal document flow (so it doesn't take up it's own space in the cell), and ii) allows the 100% height and width properites to do its thing and match the cell dimensions.
Additionally, you'll now have to position the pseudo element (either one of left: 0
or right: 0
with either a top: 0
or bottom: 0
) to make sure that the pseudo element is aligned within the table cell and not from the top left corner of the anchor element. So we now have:
td, th {
position: relative;
}
a::after {
content: '';
display: block;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}
Unfortunately, you now have a problem — the pseudo element is covering the anchor. z-index: -1
is set on the pseudo element to get it to render underneath the anchor. However, the pseudo element will be underneath a lot of other elements as well, so it will no longer have the benefits of the increased clickable area.
Setting a z-index: 0
to the table cell will address this problem by limiting the number of elements the pseudo element will be behind. By setting both position: relative
and z-index: 0
, you create a new stacking context. While the anchor will render above the table cell, its pseudo element will never render underneath the table cell now.
So finally you are left with:
td, th {
position: relative;
z-index: 0;
}
a::after {
content: '';
display: block;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
z-index: -1;
}
Some things to consider that may make this solution unsuitable for your use case:
- You cannot set
position: relative
and/or z-index
on the table cells
- You are using the pseudo elements already on the anchor
JSFiddle demo:
https://jsfiddle.net/hd7k4zau/53/