Skip to content

Using Multiple Backgrounds Images In CSS3


Before CSS3, using more than one image as a background was not easily done. The effect had to be emulated using one of the many tricks available, such as adding boxes containing images that imitated borders or adjusting styles for several elements. CSS3 comes with some very interesting properties to manage backgrounds in its Backgrounds and Borders Module, including multiple backgrounds and background image size.

Multiple Backgrounds

We can specify multiple background images for box elements using a list on the individual background properties.

The following example has two background images, one for the desert and one for the bald eagle. They are specified using a comma-separated list of values, one for each "layer" (the number of comma-separated items defines the number of background layers, the first one being on top).

Background Image

And the code will be:

[code] #background { width: 450px; height: 300px; background-image: url(baldeagle.png), url(desert.png); background-position: right top, center bottom; background-repeat: no-repeat; } [/code] [/code] 

Multiple Backgrounds Compatibility: Safari 1.3+, Chrome 2+, Firefox 3.6+, Opera 10.5+ and IE9+.

Background Size

Another new property introduced by the CSS3 Backgrounds and Borders Module is background-size. You can specify the size of background images using lengths or percentages. In the first image, the background is set to auto. In the second image, it is set to 65% or 265px width:

Background Image Size
[code] #box1 { background-size: auto; } #box2 { background-size: 295px 155px; }[/code] [/code] 

Like other background properties, background-size can accept multiple values in a comma-separated list. Apart from length and percentage, there are two other properties that you can use for background size: contain and cover. Contain will scale but preserve the image´s original proportions, as long as it is contained within the background position area; and cover will also scale and preserve proportions, but it will make the image as large as necessary to cover the positioning area.

Background Size Compatibility: Current versions of most popular browsers including Firefox, Safari, Chrome, Internet Explorer and Opera.

Defining the Background Size of Multiple Background Images

Finally, you can combine both properties, using different values for the background-size of each image (note they are still comma separated in layer order):

Defined Background Size
[code] #background { width: 450px; height: 300px; background-image: url(baldeagle.png), url(baldeagle.png), url(desert.png); background-repeat: no-repeat; background-position: 20px 100px, 200px 40px, center bottom; background-size: 70px, auto, cover; } [/code] 

In this way, we can create the appearance of a single effect while using multiple images in our websites. It's both efficient and cool.

Blog & Events

Featured Work