How do I add a color overlay to an image using CSS?

Viewed 36

im using react, html, css and material ui

I am trying to toggle between color overlay being present and not present with onclick on an image.

below is the javascript:

const About = ({imgState, setImgState}) => {

const imgTracker = () => {
    if(imgState === true){
      setImgState(false);
    }
    else if(imgState===false){
      setImgState(true);
    }
  }

...

<Box
                  className={imgState ? 'AboutImg active' : 'AboutImg notactive'}
                  component="img"
                  alt="face"
                  src={img2} 
                  onClick={imgTracker}      
                />

and below is the css:

.MidSectionTop{
    .MidSectionTopText{

    }

    .MidSectionImage{
        .AboutImg{
            height: calc(100vh * 4/12);
            width: calc(100vw * 2/12);

            &.active{
                background: rgba(0, 197, 165, 0.5);
                
            }
            &.notactive{
                background: none;
            }
        }
    }
}

my problem so far is that the image is overlayed ontop of the background color. I have tried giving z-index to the '&.active' class but it did not work out. any help grealy appreciated! Let me know what else I could provide

1 Answers

You can use what's called pseudo-elements (::before or ::after) for this.

.AboutImg{
    position: relative;
    &::after{
        position:absolute;
        left:0;
        top:0;
        right:0;
        bottom:0;
        display:block;
        content: '';
    }
    &.active::after{
        background: rgba(0, 197, 165, 0.5);
    }
    &.notactive::after{
        background: none;
    }
}
Related