0
votes

I am trying to set a background image for a div and adding a color overlay to it. With plain CSS this would look something like this:

.backgroundImage {
 background-image:
 linear-gradient(to bottom, rgba(245, 246, 252, 0.52), rgba(117, 19, 93, 0.73)),
 url('../img/backgroundimage.jpg');
 width: auto;
 height: 40vh;
 background-size: cover;
}

This CSS approach doesn't work for me though, as the component I am building will be filled dynamically (different pictures, text content etc.).

I've tried importing an image and doing the same as in the css stated above. Somehow I can set the background image but can't get the gradient overlay to work inside of my style object.

So my next approach was to wrap my div in another div and just set the gradient there. That also doesn't seem to work...

I hope someone smarter than me has an answer to this...

Cheers!

const wrapperPictureBox {
 background: "linear-gradient(to bottom, rgba(245, 246, 252, 0.52), rgba(117, 19, 93, 0.73))"
}

const pictureBox = {
 background: ` url(${backgroundimage})`,
 height: "40vh",
 backgroundSize: "cover",
};

 <div style={wrapperPictureBox}>
  <div style={pictureBox}>text</div>
 </div>
1

1 Answers

0
votes

You can go the CSS variable way. This codepen demonstrates.

Basically, in the React file:

<div style={{"--img": "url('https://images.unsplash.com/photo-1610907083431-d36d8947c8e2')"}}>text</div>

And, in CSS:

background-image: linear-gradient(to bottom, rgba(245, 246, 252, 0.52), rgba(117, 19, 93, 0.73)), var(--img);

If the gradient must also be dynamic, a similar approach should work still.