How to affect other elements when one element is hovered
Instantly style other elements on hover using CSS. Inside a container, target a child element with the :hover
pseudo-class for instant hover effects. Here's a quick example snippet:
Hovering over the #container triggers the text color of the child, identified by #child, to switch to red — it's as simple as that, without any JavaScript in the mix.
CSS relationship selectors on hover
Combine :hover
with combining selectors, namely the child (>
), adjacent sibling (+
), or general sibling (~
), to target specific elements.
Quick demo:
These select the direct child, the immediate sibling, and any sibling, when #container is hovered respectively.
Adding spice with CSS combinators
For complex hover effects, harness CSS combinators for intricate interactivity. Consider a reversed flexbox
container in this scenario:
This illuminates all preceding items in the reverse row when a container item is hovered.
Parent-child styling with CSS :has()
The :has()
pseudo-class enables styling parents based on a child's state. It goes beyond the functionality of direct relationship selectors:
This changes the background color of a div
that hosts a hovered child, even though the div
was not the element hovered directly.
Transitions, transformations, and animations on hover
Apply properties such as transitions, animations, and transformations to the hover
style for enhanced user engagement:
This example styles a sibling and applies a smooth growing effect upon hover.
Cross-browser compatibility acknowledgement
Ensure CSS hover effects are compatible with leading browsers such as Chrome, Firefox, and Edge. Remain vigilant and up-to-date with browser compatibility tables for emergent features like :has()
.
Was this article helpful?