CSS — Hover to affect Other Element (Even if Other Element is not a Child!)

You probably already know how to handle this situation:

You have two divs, one inside of the other.

#bigDiv is a parent of #smallDiv. You can listen for hover on #bigDiv, and have #smallDiv turn green.

#bigDiv:hover > #smallDiv {
background-color: green;
}

However, if #smallDiv is NOT a child of #parentDiv…..

…it no longer works!

CSS makes it a bit difficult to listen on “un-related” divs. But it can be done!!

Here’s how:

body:has(#bigDiv:hover) #smallDiv {
background-color: green;
}

Because the body is a parent of all elements, it can be used to target any element on the page!

Then, when the :has condition is triggered (hovering over #bigDiv) the animation is triggered.

--

--