Alex
Alex

Reputation: 39

Apply styles to child elements when parent is hovered

I have four divs and I want to change the background color of the three children inside the parent div on hover.

I want when hover the parent div the change the background color of #a, #b and #c with different colors each.

Any help would be much appreciated.

#a {
  background: #174259;
  height: 450px;
  width: 450px;
  display: flex;
  margin: auto;
}

#b {
  background: #C32525;
  height: 350px;
  width: 350px;
  display: flex;
  margin: auto;
}

#c {
  background: #FCC459;
  height: 250px;
  width: 250px;
  display: flex;
  margin: auto;
}

.parent>#a:hover {
  background: green;
}
<div class="parent">
  <div id="a">
    <div id="b">
      <div id="c">
      </div>
    </div>
  </div>
</div>

Upvotes: 4

Views: 50

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 371929

You want the background color of all child elements to change when you hover the parent.

But in your code, you're applying the :hover to the child:

.parent > #a:hover {
  background: green;
}

That limits the scope of your styles to that one particular child when hovered.

Instead, apply the :hover to the parent, so when hovered, all children can be targeted simultaneously:

.parent:hover > #a {
  background: green;
}

.parent:hover #b {
  background: blue;
}

.parent:hover #c {
  background: gray;
}

#a {
  background: #174259;
  height: 450px;
  width: 450px;
  display: flex;
  margin: auto;
}

#b {
  background: #C32525;
  height: 350px;
  width: 350px;
  display: flex;
  margin: auto;
}

#c {
  background: #FCC459;
  height: 250px;
  width: 250px;
  display: flex;
  margin: auto;
}

.parent:hover>#a {
  background: green;
}

.parent:hover #b {
  background: blue;
}

.parent:hover #c {
  background: gray;
}
<div class="parent">
  <div id="a">
    <div id="b">
      <div id="c">
      </div>
    </div>
  </div>
</div>

Upvotes: 1

Related Questions