0

I was trying to practice "background-image" but it didn't work correctly.

.box{
    border: 5px solid rgb(255, 20, 59);
    background-color: #ddd;
    height: 100px;
    width: 200px;
    display: inline-block;
    margin: 10px;
    padding: 14px;
    box-sizing: border-box;
    cursor: pointer;
    transition-duration: 0.5s;
}

.box:hover{
    opacity: 60%;
    transform: 2s;
}
#box1{
    background-image: url(pre-left.png);
    background-size: cover;
}
#box3{
    background-image: url(pre-right.png);
    background-size: cover;
}
#box2{
    text-align: center;
    position: relative;
    top: -52px;
    font-weight: bold;
    font-size: 43px;
}
#box2:hover + #box3{
    background-image: url(right.png);
    transition-duration: 1s;
}
#box2:hover + #box1{
    background-image: url(left.png);
    transition-duration: 1s;
}

so on I was trying to change box1 and box3 background when box 2 being hovered but what happens is changing the background of only box3 not 1

glhf
  • 3
  • 2
  • #box2:hover + #box1 use for next element not on previous element that's why box1 is not changing it's color – Nisha Jan 24 '23 at 16:03
  • https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector#:~:text=No%2C%20there%20is%20no%20%22previous,1. check this link maybe it will help you. – Nisha Jan 24 '23 at 16:10

1 Answers1

-1

The issue with your code is that the #box2:hover + #box1 selector is not correct. The + selector is used to select an element that is immediately preceded by the former element. In this case, #box1 is not immediately preceded by #box2, so this selector will not work (I guess that since it works well with #box3, so it's #box3 that comes immediately after #box2.

To solve the problems you can use JQuery, or vanilla JS, by attaching an event listner to #box2 element, and change the #box1 and #box3 background image when mouse enters #box2.

Here is an example of how you can do it using vanilla JavaScript:

// Select the elements
var box1 = document.querySelector("#box1");
var box2 = document.querySelector("#box2");
var box3 = document.querySelector("#box3");

// Add event listener to box2 element
box2.addEventListener("mouseover", function() {
    box1.style.backgroundImage = "url('left.png')";
    box3.style.backgroundImage = "url('right.png')";
});

You could also use the mouseout event listner and toggle back the background images when mouse leaves #box2.

box2.addEventListener("mouseout", function() {
    box1.style.backgroundImage = "url('pre-left.png')";
    box3.style.backgroundImage = "url('pre-right.png')";
});
Lahcen YAMOUN
  • 657
  • 3
  • 15
  • How can you tell? There's no HTML in the question. – Quentin Jan 24 '23 at 16:19
  • Since he said it worked well with #box3, and since "+" means selecting the element that comes directly after (a+b means b that comes directly after a), I had the conclusion. – Lahcen YAMOUN Jan 24 '23 at 16:20