"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > input: Can You Modify CSS on Hover for Unrelated Elements? output: How to affect irrelevant elements when CSS hovering?

input: Can You Modify CSS on Hover for Unrelated Elements? output: How to affect irrelevant elements when CSS hovering?

Posted on 2025-04-18
Browse:645

Can You Modify CSS on Hover for Unrelated Elements?

Can You Modify the CSS of a Different Class on Hover?

Many developers encounter the need to modify the CSS of one element when another unrelated element is hovered over. CSS alone often poses limitations in achieving this, prompting exploration of potential solutions.

CSS Solutions

Thankfully, CSS provides two effective approaches for this task:

  1. F as a Child of E: If the element whose CSS you want to modify (F) is a child element of the hovered element (E), use:

    .item:hover .wrapper {
        /* CSS modifications for element F */
    }
  2. F as a Sibling of E: If F is not a child of E, but rather a later sibling or its descendant in the DOM (appearing after E in the mark-up), use:

    .item:hover ~ .wrapper {
        /* CSS modifications for element F */
    }

JavaScript Alternative

Although JavaScript is generally discouraged for such simple tasks, it offers an alternative approach:

document.getElementsByClassName('item')[0].onmouseover = () => {
    document.getElementsByClassName('wrapper')[0].style.backgroundColor = "url('some url')";
};
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3