user190794
user190794

Reputation: 465

How to change background of child element when parent element is hovered?

I have the next html structure:

<div class="parent">
    <div class="child"></div>
</div>

And css:

.parent {
    width: 100px;
    height: 100px;
}

.parent:hover {
    background-color: red;
}

.child {
    width: 50px;
    height: 50px;
}

How can I change background color of child div when its parent div is hovered? Can I do it with css or I shoud use JQuery?

Upvotes: 3

Views: 1559

Answers (5)

Shiladitya
Shiladitya

Reputation: 12161

Here you go with a solution

.parent {
  background-color: green;
  width: 100px;
  height: 100px;
}

.parent:hover > .child{
  background-color: red;
}

.child {
  width: 50px;
  height: 50px;
}
<div class="parent">
    <div class="child"></div>
</div>

Hope this will help you.

Upvotes: 4

souzan
souzan

Reputation: 276

Add a new rule for .parent:hover .child

Check the example below:

.parent {
    width: 100px;
    height: 100px;
    background-color:blue;
}

.parent:hover,
.parent:hover .child  {
    background-color: red;
}

.child {
    width: 50px;
    height: 50px;
}

.child {
background-color:yellow;
}
<div class="parent">
    <div class="child"></div>
</div>

Upvotes: 1

Prawns
Prawns

Reputation: 61

If I understand you correctly, you just need to change

.parent:hover {
    background-color: red;
}

to

.parent:hover .child {
    background-color: red;
}

Upvotes: 1

Ehsan
Ehsan

Reputation: 12969

Try This:

.parent:hover .child {
  background-color: blue;
}

.parent {
  width: 100px;
  height: 100px;
}

.parent:hover {
   background-color: red;
}

.parent:hover .child{
  background-color: blue;
}

.child {
  width: 50px;
  height: 50px;
}
<div class="parent"> PARENT
  <div class="child">CHILD</div>
</div>

Upvotes: 1

charan kumar
charan kumar

Reputation: 2157

You can try this

.parent:hover .child {
   background-color: red;
}

Upvotes: 2

Related Questions