Can :hover Modify External CSS Classes?

Susan Sarandon
Release: 2024-11-02 11:12:03
Original
337 people have browsed it

Can :hover Modify External CSS Classes?

Can :hover Modify External CSS Classes?

In CSS, we can apply styling changes to elements on hover using the :hover selector. However, what if we want to modify the CSS of an element in a different class when another element is hovered?

As CSS selectors only target elements based on their hierarchy or relationships within the DOM, it's not possible to directly modify the CSS of an element outside of the current hover element's scope.

Options for Indirect Modifications

However, there are indirect approaches to achieve similar effects:

  • Parent-Child Relationship: If the element you want to modify (E) is a child of the hovered element (F), you can use the :hover selector on F to target E.
.item:hover .wrapper {
  /* Styles to be applied to '.wrapper' when '.item' is hovered */
}
Copy after login
  • Sibling Relationship: If E is a sibling of F (or a descendant of one of F's siblings), you can use the ~ sibling combinator in CSS.
.item:hover ~ .wrapper {
  /* Styles to be applied to '.wrapper' when '.item' or any of its siblings is hovered */
}
Copy after login

JavaScript Solution

If CSS solutions are not feasible, you can use JavaScript to manipulate the CSS properties of E based on the hover state of F.

<code class="javascript">document.querySelector('.item').addEventListener('mouseenter', () => {
  document.querySelector('.wrapper').style.backgroundColor = 'red';
});

document.querySelector('.item').addEventListener('mouseleave', () => {
  document.querySelector('.wrapper').style.backgroundColor = '';
});</code>
Copy after login

Conclusion

While CSS selectors alone cannot directly modify external classes, the parent-child or sibling relationship and JavaScript provide indirect solutions for achieving similar effects.

The above is the detailed content of Can :hover Modify External CSS Classes?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!