Trying to add overlay color to an img in CSS

Viewed 55

I'm trying to add an overlay color to an image I tried to use background with rgba color but I don't see the overlay color.

HTML code:

<img src="hero.jpg" alt="" class="img-hero">

CSS code:

.img-hero{
    animation-name: img-hero-animation;
    animation-duration: 900ms;
    animation-timing-function: ease-in;
    animation-fill-mode: forwards;
    transform: translateY(-20px);
    animation-delay: 1750ms;
    opacity: 0;
    
}
2 Answers

Add background using rgbawith transparency background: rgba(,62,84,0.82);

You could use the below two ways to add an overlay on an image with CSS:

  1. Use a wrapper div for the img and its :before as overlay:

.img-container {
  position: relative;
}

.img-container img {
  display: block;
  height: 100%;
  width: 100%;
  object-fit: cover;
}
.img-container:after {
  content: "";
  position: absolute;
  inset: 0 0 0 0;
  background-color: rgba(33, 22, 100, 0.4);
}
<div class="img-container"><img src="https://images.unsplash.com/photo-1659085402847-d58e44029505?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0N3x8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=60" alt="" class="img-hero"></div>

  1. Use the image as the background of a div and a linear-gradient as overlay:

.img-container {
  height:100vh;
  background: linear-gradient(rgba(33, 22, 100, 0.4), rgba(33, 22, 100, .7)), url("https://images.unsplash.com/photo-1659085402847-d58e44029505?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0N3x8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=60");
  background-size: cover;
}
<div class="img-container"></div>

Related