Home > Mobile >  background not being applied
background not being applied

Time:01-25

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

CodePudding user response:

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')";
});
  • Related