CSS Backgrounds

The CSS background properties are used to add background effects for elements.

In these chapters, you will learn about the following CSS background properties:

CSS background-color

The background-color property specifies the background color of an element.

Example

The background color of a page is set like this:

CSS background-image

The background-image property specifies an image to use as the background of an element.

By default, the image is repeated so it covers the entire element.

Example

Set the background image for a page:

CSS background-repeat

The background-repeat property sets if/how a background image will be repeated.

By default, a background-image is repeated both vertically and horizontally.

Some images should be repeated only horizontally or vertically, or they will look strange, like this:

Example

CSS background-repeat Horizontally

If the image above is repeated only horizontally (background-repeat: repeat-x;), the background will look better:

Example

CSS background-repeat: no-repeat

Showing the background image only once is also specified by the background-repeat property:

Example

Show the background image only once:

CSS background-position

The background-position property is used to set the starting position of the background image.

By default, a background-image is placed at the top-left corner of an element.

Example

Position the background image in the top-right corner:

CSS background-attachment

The background-attachment property specifies whether the background image should scroll or be fixed (will not scroll with the rest of the page):

Example

Specify that the background image should be fixed:

Example

Specify that the background image should scroll with the rest of the page:

CSS background – Shorthand property

To shorten the code, it is possible to specify all the background properties in one single property. This is called a shorthand property.

Example

Use the shorthand property to set all the background properties in one declaration: