How to add a gradient overlay to a background image using just CSS and HTML

Adding a background image to a <div> (or any other tag) is easy using CSS. Here it is (without gradient yet - scroll down for the gradient image css):

<div id='show_bg'>something here</div>
/* (Scroll down for gradient rules) */
#show_bg {
    background-image: url('images/background.jpg');
    width: 80%;
    height: 200px;
    background-size: cover;
    color: white;

Some overlaying text here...

I've put some other rules on the div to set the background image to fill the whole div (cropping if needed) with the background-size: cover. The width is 80%, so resize your browser to see how this background-size works. (It will crop the image to ensure it fits correctly).

How to add a gradient on top of a background image?

If you wanted to add a semi opaque/semi transparent colour gradient that goes on top of the background image, your first thought might be to overlay another div (or use the :after css selector).

However, the easiest way to do it is to just add another parameter to the background-image css rule.

Take a look!

<div id='show_bg_2'>something here</div>
#show_bg_2 {
    linear-gradient(to bottom, rgba(245, 246, 252, 0.52), rgba(117, 19, 93, 0.73)),
    width: 80%;
    height: 400px;
    background-size: cover;
    color: white;
    padding: 20px;

Some overlaying text here.

Both divs are using the same background image, but the second one has a linear-gradient on it. The rgba(x,y,z,o) is the colour (first three numbers = red/green/blue. The 4th param (0.52) is the opacity - 1.0 is fully visible, 0.0 is invisible).

How to add a gradient background to a div without using images

You can also easily add a gradient background to a div (or any other HTML element) without using images, using the following CSS rules.

BTW, I've set the gradient to start at red and end in blue. It might not look pretty, but it is so you can click the buttons below to swap its position, and quickly work out what direction it is facing.

Comments How to add a gradient overlay to a background image using just CSS and HTML