Fading A Background Image In

September 14th, 2012

Fading in a background image is not generally an easy task. This is because there’s no opacity state for background images in specific. Fading in a solid color background is pretty easy using RGBa – not so easy for images. There’s also the issue of when you change the opacity of body (or wrapper) element, everything inside (or the children) are effected as well. In this example, I will be using jQuery to animate the effect.

Demo


You may need to click “Run” again (the “Play” icon) to see the effect once this page has loaded.

Code

HTML

<div id="back"></div>
<h3>Stuff on top of the background.</h3>
<p>Other stuff.</p>
​

CSS

html { 
    height:100%;
}

#back {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: -100;
}​

jQuery

$(document).ready(function() {
    $('#back').animate({opacity: 0}, 0).css({'background-image': 'url(http://vaughnroyko.com/jsfiddle/back.png)'}).animate({opacity: 1}, 2500);
});

As you can see, the trick is to make a background div that covers the entire page that exists under everything. This will allow everything to layer on top of it without being effected by the opacity animation. The next trick is to not set the background image to anything by default in the CSS, otherwise, there may be a moment or two when the background image will be seen while your page is loading. You may want to use a fallback “base” image for users without JavaScript enabled. We do the rest with jQuery.

This entry was posted in Blog and tagged , , , .

5 Responses to Fading A Background Image In

Leave a Reply

*

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.

TOP