Body Background Opacity

Simple example of having a background image for the body element have opacity.

by Travis Almand

HTML

<h1>Body Background Opacity</h1>
<p>Click anywhere to load in a background image. The background will fade in up to a defined opacity using CSS transitions.</p>
<p>The background image is placed inside a :before attached to the body element which gives us the ability to control the opacity of the image. If the image was background for the body then changing opacity would be done on the body itself, which contains all the content that would be affected as well.</p>

CSS

body:before {
    background-image: url("http://lorempixel.com/640/480/cats");
    background-repeat: no-repeat;
    background-size: cover;
    content: '';
    display: block;
    opacity: 0;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: -1;
    transition: opacity 1s;
}
body.show:before {
    opacity: 0.25;
}

h1 {
    text-align: center;
}

JavaScript

$('body').on('click', function () {
    $(this).toggleClass('show');
});