Search code examples
htmlcsshovercontainersbackground-image

Hover over one div, change background over link in div using HTML/CSS


I want to change the background image of the container such that when I hover on a link 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>


Solution

  • 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>

    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.