I'm working on a React project where I have a set of cards, each with a dynamic background image loaded from a JSON file. My goal is to create a hover effect on these cards, where the background image darkens, and the title and a small description appear. I've managed to make the title and description appear using opacity transitions, but I'm facing a challenge with darkening the background image because I can't directly apply a linear gradient to it using CSS. I'm looking for a simple and efficient solution to achieve this effect without making the code too complex.
Current Code: Here's the current code structure I have for the card component:
const Card = ({ card }) => {
return (
<div className="home__prom-card" style={{ backgroundImage: `url(${card.image})` }}>
<div className="home__prom-card_price">
<h3>{card.price}</h3>
</div>
<h2>{card.name}</h2>
<p>{card.description}</p>
</div>
);
};
I've encountered difficulties in applying a darkened overlay on the background image when hovering over the card. Since the background image is loaded dynamically from a JSON file, I can't directly apply a linear gradient overlay using CSS.
my approach would be to create an absolutly positioned div inside the card and use that with the background-image property.
The structure would look like this:
(Created new home__prom-background div)
const Card = ({ card }) => {
// home__prom-card will be changed to <Link> from React Routing soon
return (
<div className="home__prom-card">
<div className="home__prom-background" style={{ backgroundImage: `url(${card.image})` }} />
<div className="home__prom-card_price">
<h3>{card.price}</h3>
</div>
<h2>{card.name}</h2>
<p>{card.description}</p>
</div>
);
};
Now for the CSS part. We add relative position to the card, so that the background div can use percentage for width and height to make it fit the full size. Also, we make the background black, so when the background's div opacity is be lowered, it looks darker.
When styling the background div, we set the position to absolute and the width and height to 100%. Finally, we add some other parameters for the background and a transition for opacity.
Don't forget to set a higher z-index for the text, so that you can see it over the background image.
For the hover effect we will change the background div's opacity when the card is hovered. Also, we will change the opacity for the text that you want to show.
.home__prom-card {
position: relative;
background-color: black;
> .home__prom-background {
position: absolute;
top: 0;left: 0;
z-index:0;
height: 100%;
width: 100%;
background-position: center;
background-size: cover;
background-repeat: no-repeat;
transition: opacity .3s ease-in-out;
}
> h2, > p, > .home__prom-card_price {
z-index:2;
}
&:hover {
> .home__prom-background {
opacity: .6;
}
> h2, > p {
opacity: 1;
}
}
}