How to change one element on a second element hover with CSS (SASS)

mitrich
2 min readJul 6, 2023

--

Recently, I have been actively studying front-end development at one of the online community courses.
One of the tasks has required to make a highlight one element on another element's hover, and it should work with the child elements too. And those elements are not in the child and parent relationship.
Certainly, you can make it with JavaScript with eventListener and add classes, but I decided to do it only with CSS (I use SASS in this example).
I didn't find complete information about this feature so here it is.

For example, if you have two div elements with another div nested like this:

<body>
<div class="first">
<div class="first__child">
</div>
</div>
<div class="second">
<div class="second__child">
</div>
</div>
</body>

You can use :has() pseudo-class for body element to choose the first element and apply your style to the second element. Because :has() pseudo-class acts as a condition, but the next style could be applied to body child elements as usual.

body
&:has(.first:hover)
.second
box-shadow: 5px 5px gray

And you can do the same thing for the child element, and also you can remove the parent hover effect.

body
&:has(.first__child:hover)
.second__child
box-shadow: 5px 5px gray
.second
box-shadow: 0px 0px

Working code example below:

--

--

mitrich

geophysics => construction & design => IT Front-end developer