How to Affect Another Element on Hover in CSS


How can we :hover over one element and change the style of another element in the DOM?

Suppose we have two div elements with an id of one and two.

We want to perform #one:hover and target a style change in #two.

In order to do this, the two elements must be directly related: either a parent-child or sibling relationship.

Parent-child relationship

Suppose #two is a child of #one.

<div id='one'>
  <div id='two'></div>
</div>

A child can also be nested further within the parent.

<div id='one'>
  <div>
    <div>
      <div id='two'></div>
    </div>
  </div>
</div>
#one:hover #two { /* style change */ }

Direct descendant (>)

Suppose #two is a direct child of #one.

A direct child cannot be nested further within the parent.

<div id='one'>
  <!-- Cannot be nested further -->
  <div id='two'></div>
</div>
#one:hover > #two { /* style change */ }

Sibling relationship (~)

Suppose #two is a sibling of #one.

<div id='one'></div>
<!-- Can have elements in between -->
<div id='two'></div>
#one:hover ~ #two { /* style change */ }

Immediate siblings (+)

Suppose #two immediately follows #one.

<div id='one'></div>
<!-- No elements in between -->
<div id='two'></div>
#one:hover + #two { /* style change */ }