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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Andrew Musholt
Andrew Musholt

Written by Andrew Musholt

Full-time web developer, part-time business owner.

Responses (1)

Write a response

yes, you are the highlight of my day. Tnx Andrew

--