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:
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 */ }
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!