I have a link and when I hover, it will get a background.
Directly in the body I can set -1
on the :before
to keep it behind the text. Inside elements which have a background this is not possible because -1
is not set behind the current element but behind all the elements.
So what can I do to fix it?
- I have a 100 links in different elements so I prefer not to add additional HTML around them.
- In real life it's not just a background, it's an animation, therefor the need of
:before
. - I prefer CSS solutions over javascript solutions.
In the example below, when hover the first link, it will get a background color. When hover the second link inside the element, it will not get a background color. Exepected result is to have a background color to the link inside the element as well, on hover.
a {
position: relative;
}
a:hover:before {
content: '';
display: block;
position: absolute;
width: 100%;
height: 100%;
background: #ccc;
top: 0;
left: 0;
z-index: -1;
}
.block {
background: #ddd;
padding: 1rem;
}
<a href="#">Link</a>
<div class="block">
<a href="#">Link in block</a>
</div>