CSS Background
In this tutorial you will learn about Cascading Style Sheets (CSS), Background, Background Color, Background image, Repeating background image, Background position and Background attachment.
Background color
To set the background color of an element, use the “background-color” property.
Example:
body
{
background-color: #FF0000;
}
This sets the background color of the document to red.
Background image
To set an image as a background, use the “background-image” property.
Example:
body
{
background-image: url(bg_image.jpg);
}
Repeating background image
To repeat a background image, use the “background-repeat” property.
The value of this property defines how the repeat will occur, the value can be one of the following:
• repeat : The image is repeated both horizontally and vertically.
• repeat-x : The image is repeated only horizontally.
• repeat-y : The image is repeated only vertically.
• no-repeat : The image is not repeated.
Example:
body
{
background-image: url(bg_image.jpg);
background-repeat: repeat-y;
}
This will repeat the image vertically.
Background position
To set the background position of a background image, use the “background-position” property.
The value of this property can be on of the following:
top left, top center, top right, center left, center center, center right, bottom left, bottom center, bottom right.
The horizontal position is specified first, and then the vertical position, If only one value is used, it sets the horizontal position only and the vertical position will be center by default.
Percentage and length values can be used also.
Example:
body
{
background-image: url(bg_image.jpg);
background-repeat: repeat-y;
background-position: 100% 0%;
}
This will use “bg_image.jpg” as a background image, place its upper-right corner in the upper-right corner of the body, and repeat it vertically.
Background attachment
To set if a background image is to be fixed or to scroll with the page use the “background-attachment” property.
The value of this property can be one of the following:
• scroll : to scroll with the rest of the page.
• fixed : to be fixed.
Example:
body
{
background-image: url(bg_image.jpg);
background-attachment: scroll;
}
This will make the background image scrolls with the rest of the page.
Using the shortcut
You can set all background properties in one declaration using the shortcut property “background”, the values have to be in the following order:
background-color, then background-image, then background-repeat, then background-attachment, and finally background-position.
Example:
body
{
background: #00FF00 url(bg_image.jpg) repeat-y fixed 100% 0;
}
This sets the background color to green, uses the image “bg_image.jpg “ as a background, repeats it vertically, and places its top right corner at the top right corner of the page.