MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create multiple background images in CSS & Javascript

In this tutorial we will learn about creating multiple background images with CSS.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

With CSS, you are able to set the background color or image of any CSS element. In addition, you have control over how the background image is displayed. You may choose to have it repeat horizontally, vertically, or in neither direction. You may also choose to have the background remain in a fixed position, or have it scroll as it does normally. Instead we'd need to nest another element for every additional background image. Now we have syntax for supporting multiple background images on one element, and here's what it looks like.

The CSS

Listing 1: Multiple backgrounds involved using multiple property assignments with multiple values, separated by a comma:

#multipleBGs {
  background: url(photo1.png),
        url(photo2.png),
        url(photo3.png)
  ;
  background-repeat: no-repeat,
             no-repeat,
             repeat-y;
            
  background-position: 0 0,
             30px 70px,
             right top;
  
  width: 400px; 
  height: 400px;
  border: 1px solid #ccc;
}

New CSS3 features that will need some extensive exploration are elements with multiple background images.

Simple Example

Simple example
Figure 1: Simple example

Here is a very simple example of a DIV element with two background images. We have a red ball at the position 30/50 and a blue gradient that is repeated along the x axis. Both images are PNGs and are composited into the DIV background with smooth alpha channel transitions.

There are multiple ways of specifying multiple images. Here we've settled on the code style below where every property is defined on a separate line for better readability.

Listing 2: Using CSS

width: 400px;
height: 180px;
padding: 10px 10px 10px 10px;
background-color: #a0e0ff;
background-image: url(../images/redball.png), url(../images/bluesky.png);
background-position: 30px 50px, 0 0;
background-repeat: no-repeat, repeat-x;

This example will work well in Firefox 3.6, Safari 4.0.4 and in the latest version of Chrome. The upcoming versions of Opera will probably also support multiple background images. Internet Explorer will completely ignore background lines in the CSS with multiple images.

Working with Animated Backgrounds

For certain animations, it is actually a very attractive way to code this, since all that has to be changed per animation cycle is only one line of CSS: the position of all the composited PNGs.

Making use of CSS:

The CSS is very similar to the first example. We've just extended the number of images from two to five. It is worth noting that images will be composited from right to left, with the right-most image being at the bottom of the image stack.

With the exception of the red ball, all images are the same width (1000 pixels) and are set to repeat along the x axis. If the starting point of these images slowly moves to the left, the ball appears to bounce along in the right direction .

Image Result

Figure 2: Image Result

Listing 3: Using CSS

width: 400px;
height: 180px;
padding: 10px 10px 10px 10px;
background-color: #a0e0ff;
background-image: url(../images/grass1.png), url(../images/redball.png), url(../images/tree1.png), url(../images/clouds1.png), url(../images/bluesky.png);
background-position: 0 0, 30px 50px, 0 0, 0 0, 0 0;
background-repeat: repeat-x, no-repeat, repeat-x, repeat-x, repeat-x;

Making use of JavaScript:

And here is a three-layer parallax scroller implemented in less than thirty lines of JavaScript, and most of it deals with the bouncing ball. The actual parallax effect took less than ten lines of code and only one style sheet change per cycle, which is really quite remarkable.

Four smoothly animated objects in one background seems to be at the edge of what is possible.However in this example three of the images are 1000x180 pixels each and all are PNGs with alpha channels. It's quite likely that this can be optimized in several different ways.

Listing 4: Using Javascript

<script type="text/javascript">
	var ball_y = 30;
	var ball_dir = 1;
	var clouds_x = 0;
	var grass_x = 0;
	var tree_x = 0;
	function ani_loop() {
		clouds_x = clouds_x - .2;
		tree_x = tree_x - .7;
		grass_x = grass_x - 1;
		ball_y = ball_y + ball_dir;
		if (ball_dir > 0  &&  ball_y > 150) {
			ball_dir = -ball_dir;
			ball_y = 150;
		}
		if (ball_dir > 0) {
			ball_dir = ball_dir * 1.0312;
		}
		if (ball_dir < 0) {
			ball_dir = ball_dir * 0.97;
		}
		if (ball_dir < 0  &&  ball_dir > -0.15) {
			ball_dir = -ball_dir;
		}
		document.getElementById('animatedback').style.backgroundPosition = grass_x+'px 0, 30px '+ball_y+'px, '+tree_x+'px 0, '+clouds_x+'px 0, 0 0';
		t = setTimeout('ani_loop()',10);
	}
	ani_loop();
</script> 

Working with Many Animated Backgrounds

We can actually now also use CSS Transitions with a small event-driven script to create a similar effect that leaves most of the JavaScript bandwidth free for other things. This may look very similar to the full JavaScript version, but works very differently.

Making use of CSS:

The first class in the CSS is always applied to our DIV and sets the basic multiple background parameters.

When the page loads, .multibackstart has also been applied, setting the original start positions for all backgrounds. Once the page is done loading a script is being called and replaces .multibackstart with .multibackprocess, which kicks off the parallax scrolling. The parallax effect results from the different target positions for the different layers while the duration is kept the same.Some layers have to move faster than others.

Listing 5: Using multiback, multibackstart and multibackprocess function

.multiback {
	width: 400px;
	height: 180px;
	padding: 10px 10px 10px 10px;
	background-color: #a0e0ff;
	background-image: url(images/grass1.png), url(images/tree1.png), url(images/clouds1.png), url(images/bluesky.png);
	background-repeat: repeat-x, repeat-x, repeat-x, repeat-x;
}

.multibackstart {
	background-position: 0 0, 0 0, 0 0, 0 0;
}

.multibackprocess {
	-moz-transition-property: background-position;  
	-moz-transition-duration: 30s;
	-moz-transition-timing-function: linear;
	-webkit-transition-property: background-position;  
	-webkit-transition-duration: 30s;  
	-webkit-transition-timing-function: linear;
	-o-transition-property: background-position;  
	-o-transition-duration: 30s;  
	-o-transition-timing-function: linear;
	transition-property: background-position;  
	transition-duration: 30s;  
	transition-timing-function: linear;
	background-position: -5400px 0, -4600px 0, -3800px 0, -3000px 0;
}

Make use of JavaScript:

In the script we first define some basic global variables. target_base sets the general speed (further is faster) and target_difference influences the parallax effect. These initial parameters match the target positions in the .multibackprocess class above.

start_animation() is being called on page load and calls set_animation() which will kick off the CSS transition and returns the DIV object that the transition has been applied to. We then listen to the transitionend event (webkitTransitionEnd for webkit) and when the event fires after 30 seconds (transition duration set in the CSS), we fire reset_animation().

When reset_animation() is being called, we know that the transition has moved the background layers to their respective target positions. We increment the multiplier and move the target for the transition further down along the x-axis by the same distance as the initial transition. This forces the transition to continue at the same speed.

What makes this method incredibly attractive is that we can handle relatively complex animations and only have to dedicate a few script cycles every thirty seconds (in this example) to control the animation. Currently, the resulting animation is a little bit less smooth than the full JavaScript controlled animation, but CSS transitions are still relatively new in the browsers.

Listing 6: Using Javascript

<script type="text/javascript">
var multiplier = 1;
var target_difference = 800;
var target_base = 3000;

function start_animation() {
	var func_el = set_animation();
	func_el.addEventListener('transitionend', reset_animation, true);
	func_el.addEventListener('webkitTransitionEnd', reset_animation, true);
}

function set_animation() {
	var el = document.querySelector('div.multiback');
	el.className = 'multiback multibackprocess';
	return el;
}

function reset_animation() {
	multiplier++;
	var el = document.querySelector('div.multiback');
	el.style.backgroundPosition = '-'+((target_base + target_difference*3)*multiplier)+'px 0, -'+((target_base + target_difference*2)*multiplier)+'px 0, -'+((target_base + target_difference)*multiplier)+'px 0, -'+(target_base*multiplier)+'px 0';
}
</script>	

Conclusion

This was an interesting tutorial where we made use of both CSS and JavaScript to create background images which are important to make attractive images.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login