How to put a background image with gradient (css)

A very common task in web development is putting a color or a gradient over the background image. The below is what I always use.

In the below examples, I have a div in my HTML with a class of jumbo.

Here is a codepen.

Example Background Image with Linear Gradient:


.jumbo {
  height: 100vh;
  background-image: linear-gradient(to bottom left, rgba(100, 130, 52, 0.7), rgba(100, 100, 34, 0.7)), url("https://images.pexels.com/photos/531880/pexels-photo-531880.jpeg");
  background-size: cover;
}

Example Background image without a linear gradient

If you don’t need a gradient, you should still use linear-gradient because the background-image property doesn’t work with just rgba. So just set both rgba colors equal.


.jumbo {
  height: 100vh;
  background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url("https://images.pexels.com/photos/531880/pexels-photo-531880.jpeg");
  background-size: cover;
}

How does it work?

The height of 100vh makes the div full screen. Of course, you can change this to whatever height you need.

The background-image property can set one or more images. For the first one we set the linear-gradient and for the second one we set the actual image. We put the linear gradient first so it stays on top.

Lastly, I set the background-size to cover so that the image covers the entire container. Of course you can keep further customizing by setting the background-position or add a clip-path, etc.