While CSS doesn't allow you to target parent elements directly, there are alternative methods to achieve the desired effect.
If you want the background color of a parent element to change when a child is hovered over, consider using the spread-radius
value of the CSS box-shadow
property.
You can create a large spread radius to alter the color of the surrounding area, visually similar to changing the parent element's background color.
div {
overflow: hidden; /* 1 */
}
a:hover {
box-shadow: 0 0 0 1000px red; /* 2 */
}
/* Additional styles for decoration */
div {
height: 150px;
width: 150px;
border: 1px dashed black;
display: flex;
justify-content: center;
align-items: center;
}
<div>
<a href="http://www.stackoverflow.com/">Anchor Text</a>
</div>
Key Points:
- Use
overflow: hidden
to restrict the child's box shadow
- The values for
box-shadow
are as follows:
<box-shadow> : <offset-x> <offset-y> <blur-radius> <spread-radius> <color>
- offset-x: horizontal distance from the element
- offset-y: vertical distance from the element
blur-radius
: increases the size and transparency of the shadow
spread-radius
: expands the shadow without fading
In this scenario, the first three values are irrelevant.
To achieve the desired effect, increase the spread-radius
significantly and then mask it with the container using overflow: hidden
.
What if there's another element in the container?
<div>
<h2>Hello</h2>
<a href="http://www.google.com">Anchor Text</a>
</div>
div {
overflow: hidden;
}
a:hover {
box-shadow: 0 0 0 1000px red;
}
div {
height: 150px;
width: 150px;
border: 1px dashed black;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
<div>
<h2>Hello</h2>
<a href="http://www.stackoverflow.com/">Anchor Text</a>
</div>
You can assign a z-index
to the sibling element.
h2 { z-index: 1; }
Since the elements are within a flex container in this example, they do not need to be positioned explicitly for z-index
to take effect. Learn more here.
h2 { z-index: 1; }
div {
overflow: hidden;
}
a:hover {
box-shadow: 0 0 0 1000px red;
}
div {
height: 150px;
width: 150px;
border: 1px dashed black;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
<div>
<h2>Hello</h2>
<a href="http://www.stackoverflow.com/">Anchor Text</a>
</div>