demosthenes.info

Independent notes on CSS, SVG, animation and front-end design.

Articles / Article

A Quick and Simple CSS-Only Method For Fading Background Images

Making up for the absence of background-opacity

There’s no background-opacity control in CSS yet, but there’s an easy way to fake it, by using multiple background images. The trick is to manipulate the fact that the background-image property will also take a CSS color… which includes rgba.

A “washed out” background can be used to enhance the contrast between text and the image behind it. Naturally, you can reduce the opacity of the image by processing it in PhotoShop, but that usually takes repeated back-and-forth experimentation between the browser and graphics application, whereas writing the visual changes in CSS is far more direct and efficient.

Background image, before layering

The order of backgrounds in a multiple background declaration is from front to back, so we specify the composite photograph (from work by Thomas Shahan) last in the banner for the fictional entomologist blog Bug Crazy:

h1 { font-family: Calluna Sans, Arial, sans-serif; color: #fff;
background: -webkit-linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5)), url('bugs.jpg');
background: -moz-linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5)), url('bugs.jpg');
background: linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5)), url('bugs.jpg');
font-size: 5rem; padding: 2rem; text-align: center; background-repeat: no-repeat; background-size: cover; word-spacing: 5rem; margin-top: 0; }
<h1>Bug Crazy</h1>

That produces the result you see at the top of the page; changing the “darkness” of the background image is simply a matter of raising the last value (alpha) in the rgba color value for the background image layer.