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

Can You Modify CSS on Hover for Unrelated Elements?

Patricia Arquette
Release: 2024-11-02 11:36:31
Original
972 people have browsed it

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 */
    }
    Copy after login
  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 */
    }
    Copy after login

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template