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 , , , .

4 Responses to Fading A Background Image In

November 17th, 2013
Jacob says:

For some reason, when I use this, I can no longer style the elements on top of the background (ex: and ) Any thoughts?

Reply
November 17th, 2013
Vaughn Royko says:

I tried to style the elements on the JSFiddle example with no issues. Not sure what your issue could be.

Reply
August 12th, 2015
Perry says:

I managed to get your technique to work but can’t seem to get the background image to repeat-y. What am I doing wrong?

.canvas {
position: absolute;
left: 0px;
top: 0px;
right: 0px;
bottom: 0px;
z-index: -100;
width: auto;
height: auto;
-webkit-transform: none;
-ms-transform: none;
transform: none;
}

$(document).ready(function() {

“use strict”;

$(‘.canvas’).animate({opacity: 0}, 0).css({‘background-image’: ‘url(images/technology3.jpg)’})
.animate({opacity: 1}, 2500);

});

Reply
August 13th, 2015
Vaughn Royko says:

Not sure, but maybe try adding a background-repeat: repeat; to your .canvas selector. Also, it’s possible your canvas is is not repeating due to it’s width/height since you have it set to auto, instead of say, 100%.

If you send a jsfiddle or something I can help further.

Reply

Leave a Reply

*

*

TOP