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