How to Use the CSS Background Shorthand Property
See CSS: Tips and Tricks for similar articles.
The background property is used to set the individual properties for background-color, background-image, background-repeat, background-attachment, and background-position. Note that order matters (although some browsers may show some leniency). Learn how to use the CSS background shorthand property in the following steps.
- The syntax for the
backgroundproperty is as follows:
The CSS initial values for theselector { background: background-color background-image background-repeat background-attachment background-position; }backgroundproperty are as follows:Property Initial Value background-colortransparentbackground-imagenonebackground-repeatrepeatbackground-attachmentscrollbackground-position0% 0% - When using shorthand for the background property, there are some things you need to be aware of:
- The background color renders first then the background image is placed over the color. This can be exploited.
- You can use
backgroundin place ofbackground-colorto set the background color (e.g.,background: red;). - You can use
backgroundin place ofbackground-imageto set the background image (e.g.,background: url(bg.gif);).
- The following example demonstrates the background shorthand property:
This code renders the following:<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>CSS Background shorthand</title> <style type="text/css" media="screen"> div { margin: .75em; padding: .5em; height: 50px; border: 1px solid lightgrey; } div.one { background: #ccc; /* shorthand for background-color */ } div.two { background: url('Images/block.gif'); /* shorthand for background-image */ color: white; } div.three { background: #ccc url('Images/block.gif') repeat-x scroll 0% 0%; /* uses all available values */ color: white; } div.four { background: #ccc url('Images/block.gif') no-repeat scroll 20% 75%; /* different background position values */ } div.five { background: #ccc url('Images/block.gif') no-repeat scroll bottom center; /* and still different background position values */ } </style> </head> <body> <div class="one">This background sets only the color.</div> <div class="two">This background sets only the image.</div> <div class="three">This background sets all available values.</div> <div class="four">This background modifies the background-repeat and the background-position values.</div> <div class="five">This background modifies the background-position values.</div> </body> </html>
