Explain Codes LogoExplain Codes Logo

How to affect other elements when one element is hovered

css
responsive-design
best-practices
transitions
Anton ShumikhinbyAnton Shumikhin·Feb 14, 2025
TLDR

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:

#container:hover #child { color: red; /* The color of rebellion, resistance, and err... tomatoes? */ }

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:

#container:hover > #child-direct { // Little rebel stirring things up border: 2px solid blue; } #container:hover + #sibling-next { // Standing by side in solidarity font-weight: bold; } #container:hover ~ #any-sibling { // Collective effort to drive change opacity: 0.75; }

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:

.container { display: flex; flex-direction: row-reverse; // Row, row, row your elements, mildly against the stream } .container-item:hover ~ .container-item { background-color: salmon; // Just keep swimming until you turn salmon! }

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:

div:has(>#hover-child:hover) { background-color: lemonchiffon; // When life gives you hovered children, you make lemonchiffon! }

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:

.sibling:hover { transform: scale(1.5); // Size matters not... okay, maybe it does a little. transition: all 0.3s ease; // Slow transition... like real life. }

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().