I want to change the background image of the container such that when I hover on the text in the div, the background image changes.
Reading in stackoverflow and other sources, this should work, but I have tested in both Chrome and Edge. Neither is working at the moment.
#container {
width: 50%;
height: 300px;
position: relative;
}
#text {
position: absolute;
font-size: 3em;
z-index: 5;
}
#text:hover~#background {
background-image: url("http://lorempixel.com/400/200/food/");
}
#background {
width: 100%;
background-image: url("http://lorempixel.com/400/200/animal/");
background-position: center;
background-size: cover;
height: 100%;
opacity: 0.5;
position: absolute;
}
<div id="container">
<div id="background"></div>
<div id="text"><a href="http://www.google.ca">Google</a></div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
If you are able to change your HTML, swap the background and text elements.
Then hovering on the text element can pick up its sibling element which is the background as it comes after it in the flow:
#container {
width: 50%;
height: 300px;
position: relative;
}
#text {
position: absolute;
font-size: 3em;
z-index: 5;
}
#text:hover~#background {
background-image: url("https://picsum.photos/id/1015/300/300");
}
#background {
width: 100%;
background-image: url("https://picsum.photos/id/1016/300/300");
background-position: center;
background-size: cover;
height: 100%;
opacity: 0.5;
position: absolute;
}
<div id="container">
<div id="text"><a href="http://www.google.ca">Google</a></div>
<div id="background"></div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
But an alternative way could be to put your background images onto a pseudo element and cut out the need for a div background which isn't really needed to be a 'proper' element as it is just decoration.
CodePudding user response:
#background {
background-image: url("http://lorempixel.com/400/200/sports/");
height:200px;
}
#container:hover > div:not(:hover){
background-image: url("http://lorempixel.com/400/200/food/");
}
#text{height:0;}
<div id="container">
<div id="background">abc</div>
<div id="text"><a href="http://www.google.ca">Google</a></div>
</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>