Home  >  Article  >  Web Front-end  >  Can You Modify CSS on Hover for Unrelated Elements?

Can You Modify CSS on Hover for Unrelated Elements?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 11:36:31796browse

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')";
};

The above is the detailed content of Can You Modify CSS on Hover for Unrelated Elements?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn