Fixed background and animation

I ran into a peculiar problem while designing a website for my client. They had professional photos taken and I liked them very much, so I decided I would use them as a fixed background that would stretch to the full width and height of the screen regardless of the website’s visitor resolution. That is done easily with CSS3:

background-attachment: fixed; 
background-position: center center; 
background-repeat: no-repeat; 
background-size: cover;

However, I liked more than one of those pictures so I wanted to use more of them on top of each other and then let jQuery fade them in a loop, which can also create interesting visual effects. That is a problem however, because you can have only one background image, of course. As a workaround, I used a div that is below all the content and is stretched to the full width and height.

.my_background_div_container {
	position: absolute; 
	height: 100% !important; 
	background-attachment: fixed; 
	background-position: center center; 
	background-repeat: no-repeat; 
	background-size: cover; 
	width: 100%;
}
#background_1 { 
	background-image: url('../img/bg01.jpg'); 
	z-index: 9;
	}
#background_2 { 
	background-image: url('../img/bg02.jpg');  
	z-index: 8;
	}
#background_3 { 
	background-image: url('../img/bg03.jpg');  
	z-index: 7;
	}

The fixed background div works just fine as long as your content is fixed as well, ie. a small login form in the middle of the screen. But once the content extends the page and you scroll down, the background div remains at the top.

The only way to avoid this is to use javascript to move the container div along with the user scrolling down:

$(window).scroll(function() {
    	var p = $(window).scrollTop();
		$("#background_1").offset({ top: p, left: 0 });
		$("#background_2").offset({ top: p, left: 0 });
		$("#background_3").offset({ top: p, left: 0 });
	});

This solution has several drawbacks, though. First of all, it’s very resource-hungry. Second, there are some visual glitches in some browsers. It works flawlessly in FF 11, but there are lags in Chromium 18. As for IE, I didn’t even dare to have a look 🙂

Anyway, due to those glitches, I decided to use the fade effect only on the home page of the website, which has fixed height. For the sub pages, there is a randomly chosen image that stretches on the whole screen, but there is no fade effect. I think it is a fair compromise between visually attractive effects and usability.

I keep the original version, which was resource hungry and had problems in some browsers, here: https://www.hutsky.cz/code_examples/post_904/

Leave a Reply