Sometimes we need to add a colored mask on the background image of an element. Here’s how to apply background color on a background image in CSS
We can use the background-image
CSS property to apply background color on the background image. First, provide a linear-gradient
and then the background image URL. Here is the syntax - background-image: linear-gradient(0deg, transparent, red), url(“link to image”);
Also Read - Make a cool Image hover effect using CSS only
Before moving on to the explanation and example, I think we should know a little about the CSS background-image
property and the functions we will be using in this article.
Property or Function | Details |
---|---|
background-image CSS property | We use the background-image CSS property to set one or more background images for an HTML element. |
linear-gradient() CSS function | We use the linear-gradient() CSS function to create a linear gradient image using two or more colors. |
rgba() CSS function | We use the rgba() CSS function to define color in Red, Green, Blue, and Alpha model. |
url() CSS function | We use the url() CSS function to include a resource by absolute, relative, blob, or data url. |
Why use the linear-gradient function with the background-image property in CSS?
Because the background-image property accepts image as its value and the linear-gradient function creates an image.
How to apply background color on the background image in CSS?
Since we can create a transparent image using the CSS gradient functions we can use that on top of our image to apply this effect.
Syntax - background-image: linear-gradient(0deg, transparent, red), url(“link to image”);
Notice that the linear-gradient is applied before the image. So it remains on top of the image.
Example
Heres an example
body {
background-image: linear-gradient(0deg, transparent, red),
url(“https://picsum.photos/200”);
}
Conclusion
While there are more than one ways to apply color over a background image in CSS I think this is the most easiest way to do it.