0

I am trying to change the color of box2 when I hover over box1 but its not working. please help me why this is not working.

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.box1,
.box2 {
  width: 100px;
  height: 100px;
}

.box1 {
  background-color: teal;
  /*   position:relative; */
}

.box2 {
  background-color: tomato;
  position: relative;
  left: -50px;
}

.box1:hover .box2 {
  background-color: green;
}
<div class="box1"></div>
<div class="box2"></div>
Gerard
  • 15,418
  • 5
  • 30
  • 52
Devrishi
  • 27
  • 5

4 Answers4

4

.box1:hover .box2 indicates the .box2 selector which is included in .box1 when hovered. So there is no selector for that.

In your case, you should use .box1:hover ~ .box2 which indicates the .box2 selector next to .box1 selector.

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.box1, .box2{
  width: 100px;
  height: 100px;
}
.box1 {
  background-color: teal;
/*   position:relative; */
}
.box2 {
  background-color: tomato;
  position: relative;
  left: -50px;
}

.box1:hover ~ .box2{
  background-color: green;
}
<div class="box1"></div>
<div class="box2"></div>
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
3

You need to use the + selector to access a sibling. Your code was looking for box2 as a child element

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.box1,
.box2 {
  width: 100px;
  height: 100px;
}

.box1 {
  background-color: teal;
  /*   position:relative; */
}

.box2 {
  background-color: tomato;
  position: relative;
  left: -50px;
}

.box1:hover + .box2 {
  background-color: green;
}
<div class="box1"></div>
<div class="box2"></div>
Gerard
  • 15,418
  • 5
  • 30
  • 52
1

You just have to add ~ after hover

.box1:hover ~ .box2 {
        background-color: green;
      }
Ghayas Ud Din
  • 315
  • 2
  • 14
1

.box1:hover .box2 targets all elements within box1 when it is hovered over.

However, you'd like to make it so it targets elements next to box1. So you can use the + symbol instead!

The + symbol targets the element after the first element.

So please change it to .box1:hover + box2

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.box1,
.box2 {
  width: 100px;
  height: 100px;
}

.box1 {
  background-color: teal;
  /*   position:relative; */
}

.box2 {
  background-color: tomato;
  position: relative;
  left: -50px;
}

.box1:hover + .box2 {
  background-color: green;
}
<div class="box1"></div>
<div class="box2"></div>
corn on the cob
  • 2,093
  • 3
  • 18
  • 29