Applying a Colored Overlay to a Background Image

css
Table of Contents

I recently worked on a project that had a background image covering the entire body of the page. One of the differences was that the background also needed a colored overlay, in this case a black overlay with slight opacity.

I would normally do this using an absolutely positioned element stretching to all 4 corners of the page with a z-index lower than the <main> content of the page, but then you end up constantly working about stacking context problems.

After some digging I realised that you can pass multiple values to the background-image CSS property.

body {
    background-image: url('bg-img.jpg'), ...;
}

This makes it really simple to apply a colored overlay using a linear-gradient() between 2 identical colors, combined with the background-blend-mode property.

body {
    background-image: url('bg-img.jpg'), linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5));
    background-blend-mode: overlay;
}

This will place the gradient on top of the background image.

NOTE

I've found that overlay works best with dark shades. If you're using a brighter color, you might also want to try multiply.

If you use Tailwind, then you can use the bg-blend-overlay class to apply the blend mode.

Enjoyed this post or found it useful? Please consider sharing it on Twitter.