Home > Net >  How can I overlay a background image in a react component?
How can I overlay a background image in a react component?

Time:11-30

I've got an image inside a component and I want to overlay a 0.6 white background on top of it.

import background from "../images/pageBG2.png"; //import an image for bg use

var collectionWindowStyle = {
div:{
    
    
    backgroundImage: `url(${background})`,
    backgroundPosition: 'center',
    backgroundSize: 'cover',
    
    background: 'rgba(255,255,255,0.5)',

    color: "white",
    margin: "5px",
    padding: "5px",
}
,
h1:{
    color: "grey"
},

}

So my thoughts were that if I used "background" after my image, that would overlay pure white on it, but the alpha would allow the image to appear somewhat washed out. All that happens in my react app is that the image is entirely white. What can I do?

And then call this in the component itself

const Bookcollection  = () => {

    return(
        <div style={collectionWindowStyle.div}>
        ...

Tried googling it but didn't find anything by myself.

CodePudding user response:

Set the component’s position to relative and place a div inside. Then give that child div a position of absolute and inset 0. Then give that same div a white transparent background.

CodePudding user response:

By writing this you are overwriting the image and replacing it with white background

 backgroundImage: `url(${background})`,
    backgroundPosition: 'center',
    backgroundSize: 'cover',
    
    background: 'rgba(255,255,255,0.5)',

You can create a overlay by this :

div:{
    backgroundImage: `url(${background})`,
    backgroundPosition: 'center',
    backgroundSize: 'cover',  
    color: "white",
    margin: "5px",
    padding: "5px",
     '&::before': {
      content: "",
      position: "absolute",
      left: 0,
      right: 0,
      top: 0,
      bottom: 0,
      background: "rgba(255,255,255,.5)",
    }
}

The css looks like this :

div:{
....
}

div:before {
  content: "";
  position: absolute;
  left: 0; 
  right: 0;
  top: 0; 
  bottom: 0;
  background: rgba(255,255,255,.5);
}
  • Related