CSS3 Backgrounds

Course- Javascript >

CSS3 contains several new background properties that allow more control of the background element.

In this section you’ll learn about the background-size and backgroundorigin properties, as well as how to use multiple background images.

The background-size Property

The background-size property adds a new feature to CSS that allows you to set the size of your background images using lengths, percentages, or either of two keywords, contain or cover.

Specifying the background size using lengths and percentages behaves as you might expect. For each background image, two lengths or percentages can be supplied, relating to the width and height, respectively. (When you use percentages, these relate to the space available for the background, not to the width and height of the background image.)

Specifying the background size using lengths and percentages behaves as you might expect. For each background image, two lengths or percentages can be supplied, relating to the width and height, respectively. (When you use percentages, these relate to the space available for the background, not to the width and height of the background image.)

#div1 {
background-size: 400px;
background-image: url(lake.png);
width: 400px;
height: 250px;
border-radius: 25px;
}                 
                 

Here I’ve set the background width equal to the size of the <div> element (I’ve also rounded the corners for good measure).

Background setting in css3

The background-origin Property

The background-origin property is used to set how the position of a background in a box is calculated.

It takes one of three values: padding-box, border-box, or content-box. When you supply a value of padding-box, the position is relative to the upper-left corner of the padding edge. With border-box it’s relative to the upper-left corner of the border, and content-box means the background is positioned relative to the upper-left corner of the content.

Multiple Background Images

CSS3 lets you use multiple background images for box elements, simply by employing a comma-separated list. The order of the list is important, with the first value supplied representing the layer closest to the user, and subsequent entries in the list being rendered as layers successively further behind it. Here’s an example:

#div1 {
width: 600px;
height: 350px;
background-image: url(boat.png), url(lake.png);
background-position: center bottom, left top;
background-repeat: no-repeat;
}                 
                 
Using multiple images in CSS3 backgrounds

Browser support for the multiple backgrounds feature is already quite established, with Mozilla Firefox (3.6+), Safari/Chrome (1.0/1.3+), Opera (10.5+), and Internet Explorer (9.0+) offering support.