I’ve added a background linear gradient on my image, but regardless of what I try, it never actually shows. Can anyone suggest where I’m going wrong?
.card {
height: 500px;
}
.card img {
height: 100%;
width: 100%;
background: linear-gradient(280.03deg, rgba(44, 39, 39, 0.76) 17.44%, rgba(44, 39, 39, 0) 53.16%);
}
.card .content {
position: absolute;
bottom: 32px;
color: white;
}
<div class="container">
<div class="card">
<img src="https://placekitten.com/1440/671" />
<div class="content">
<p>
Why does my linear gradient background not work?
</p>
</div>
</div>
</div>
3
Answers
Your image has
height: 100%; width: 100%;
defined in its CSS rule – there is no space for a background to appear, the image fills the container completely, and even if it wouldn’t, the background only applies to the image itself in its defined size, which would always "cover" the background.The only case where a background color or gradient would appear that is defined for the image itself would be when the image has transparent areas in it (which would also require an according image format like .PNG)
The background is actually displayed behind your image. You can see it in a split second right before the image loads. In order to see the gradient over the image, you’d have to position an absolute div over your image like this:
As stated in another answer, the background is shown behind the actual image.
Solution
You could create an overlay using a CSS pseudo element (
::before
or::after
). This prevents you from having to add extraneous HTML elements.See the following snippet:
Alternative solution
If you don’t need to have an
img
element in the HTML (i.e. in case the image has no actual semantic value to the page, but is purely used for styling), it’s recommended to have the image as a background in CSS. You can then use multiple backgrounds via CSS to have both the image and the gradient as a background.