Search code examples
htmlcssopacity

Make div cover whole image


I'm trying to create an opaque div with a slight colour over an image. I can't seem to get it to fit exactly over the whole image. I've tried so many different variations and the following is the best I can come up with. I know it's probably something simple but I think I need some help lol.

.old{
    position: relative;
}

.cover{
 background-color: blue;   
 width: 100%;
 height: 200vh;
 position: absolute;
 top: 0;
 left: 0;
 z-index: 1;
 opacity: 0.5;
}
<div class ="cover">
    
</div>

<img class="old" src="https://www.technogies.com/wp-content/uploads/2018/10/Elderly-At-Using-Technology.jpg" style="width:100%">


Solution

  • I think this is what you want, basically I added a container for both the image and the div and forced the div position to be relative to container <div>

    body {
      margin: 0;
    }
    .container {
     position: relative;
    }
    
    .cover {
     background-color: blue;   
     width: 100%;
     height: 99%;
     position: absolute;
     top: 0;
     left: 0;
     opacity: 0.5;
    }
    <div class="container">
      <div class ="cover">
    
      </div>
    
      <img class="old" src="https://www.technogies.com/wp-content/uploads/2018/10/Elderly-At-Using-Technology.jpg" style="width:100%">
    </div>