Home > Article > Web Front-end > 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:
.item:hover .wrapper { /* Styles to be applied to '.wrapper' when '.item' is hovered */ }
.item:hover ~ .wrapper { /* Styles to be applied to '.wrapper' when '.item' or any of its siblings is hovered */ }
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>
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!