Change color of sibling elements on hover using CSS

You can make a sibling that follows an element change when that element is hovered, for example you can change the color of your a link when the h1 is hovered, but you can’t affect a previous sibling in the same way.

h1 {
    color: #4fa04f;
}
h1 + a {
    color: #a04f4f;
}
h1:hover + a {
    color: #4f4fd0;
}
a:hover + h1 {
    background-color: #444;
}
<h1>Heading</h1>
<a class="button" href="#">The &quot;Button&quot;</a>
<h1>Another Heading</h1>

We set the color of an H1 to a greenish hue, and the color of an A that is a sibling of an H1 to reddish (first 2 rules). The third rule does what I describe — changes the A color when the H1 is hovered.

But notice the fourth rule a:hover + h1 only changes the background color of the H1 that follows the anchor, but not the one that precedes it.

This is based on the DOM order, and it’s possible to change the display order of elements, so even though you can’t change the previous element, you could make that element appear to be after the other element to get the desired effect.
Note that doing this could affect accessibility, since screen readers will generally traverse items in DOM order, which may not be the same as the visual order.

Leave a Comment