Home > Web Front-end > CSS Tutorial > Can CSS Modify One Class\' Style on Hovering Over Another?

Can CSS Modify One Class\' Style on Hovering Over Another?

Mary-Kate Olsen
Release: 2024-11-03 05:34:30
Original
706 people have browsed it

Can CSS Modify One Class' Style on Hovering Over Another?

Using CSS to Modify Class Style on Hover

Can a single CSS rule be used to alter the CSS properties of one class when hovering over an element from a separate class? Is it possible to create a rule such as:

.item:hover .wrapper { /*some css*/ }
Copy after login

where .wrapper is not directly contained within .item, but rather located elsewhere in the document?

CSS Solution

Yes, this is possible using CSS selectors. There are two approaches you can take when using :hover to modify the style of another element:

1. Descendant or Child Element

If .wrapper is a child element of .item, you can use this selector:

.item:hover .wrapper {
    /* CSS properties to change */
}
Copy after login

2. Sibling Element

If .wrapper is a sibling element of .item, appearing after .item in the DOM, you can use this selector:

.item:hover ~ .wrapper {
    /* CSS properties to change */
}
Copy after login

JavaScript Solution

While JavaScript is not necessary for this simple task, you can use it to achieve the desired effect. Here is an example:

document.getElementsByClassName('item')[0].addEventListener('mouseover', function() {
  document.getElementsByClassName('wrapper')[0].style.background = "url('some url')";
});
Copy after login

Additional Information

It's important to note that your example menu elements appear to be using distinct classes. When hovering over an element, its submenu appears to the right as an overlay. The class controlling the background of the submenu is named "wrapper." To achieve desired effect, use the sibling selector approach described above.

References

  • [CSS 2.1 selectors](https://www.w3.org/TR/CSS21/selectors.html)

The above is the detailed content of Can CSS Modify One Class\' Style on Hovering Over Another?. 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