CSS3 brings several fresh properties for tweaking an element's background, including background clipping, multiple backgrounds, and the option to adjust background size.
This section will walk you through all the new background features of CSS3. For additional background-related properties, check out the CSS background tutorial.
background-size
PropertyThe background-size
property lets you specify the size of background images. In pre-CSS3 days, background image sizes were tied to the actual image dimensions. You can now define the size using pixels, percentages, or keywords like auto
, contain
, and cover
. Negative values are not permitted.
.box {
width: 250px;
height: 150px;
background: url("images/sky.jpg") no-repeat;
background-size: contain;
border: 6px solid #333;
}
Tip: Use the background-size
property to create full-size background images that scale according to the viewport size or browser width.
background-clip
PropertyThe background-clip
property determines if an element's background extends beneath its border or not. It can take three values: border-box
, padding-box
, or content-box
.
.box {
width: 250px;
height: 150px;
padding: 10px;
border: 6px dashed #333;
background: orange;
background-clip: content-box;
}
Check out the tutorial on CSS box model to learn more about element boxes.
background-origin
PropertyThe background-origin
property specifies where background images start from. It accepts the same values as background-clip
: border-box
, padding-box
, or content-box
.
.box {
width: 250px;
height: 150px;
padding: 10px;
border: 6px dashed #333;
background: url("images/sky.jpg") no-repeat;
background-size: contain;
background-origin: content-box;
}
Note: The background-origin
property is disregarded if the value of background-attachment
is set to 'fixed'
.
CSS3 lets you apply multiple backgrounds to a single element, stacking them on top of each other. The number of layers depends on the number of comma-separated values in the background-image
or background
shorthand property.
.box {
width: 100%;
height: 500px;
background: url("images/birds.png") no-repeat center, url("images/clouds.png") no-repeat center, lightblue;
}
The initial value in the list of backgrounds, which is the background-image
'birds.png', will be displayed on top, while the last value, 'lightblue', will be at the bottom. Only the final background can have a background-color
.