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>

0

4 Answers 4

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>

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>

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>

1

You just have to add ~ after hover

.box1:hover ~ .box2 {
        background-color: green;
      }

Not the answer you're looking for? Browse other questions tagged or ask your own question.