× Introduction Applying CSS CSS Syntax CSS Selectors Grouping Color Background CSS Fonts CSS Text CSS Links Gradients The Box Model Margin and Padding Border Outline Measurement Units Dimension CSS Quick Reference Examples Projects eBooks






Background

In this tutorial you will learn how to define background styles for an element using CSS. The background properties can add background effects. None of these properties inherits and they can be applied to any elements.

background-color

The color of an element’s background is set with the background-color property. By default, its value is set to transparent.

Example: Try It

body {
    background-color: #f0e68c;
}

background-image

Background-image specifies an image to use as a background with the url function.

Example: Try It

body {
   background-image: url("images/books.jpg");
}

background-repeat

By default, the background image repeats itself both horizontally and vertically. This can be changed with the background-repeat property to make the background repeat (repeat), only horizontally (repeat-x), only vertically (repeat-y), or not at all (no-repeat).

Example: Try It

body {
    background-image: url("images/gradient.png");
    background-repeat: repeat-x;
}

Background Attachment

Background attachment determines whether a background image is fixed or scrolls with the rest of the page.

Example: Try It

body {
    background-image: url("images/background.jpg");
    background-repeat: no-repeat;
    background-attachment: fixed;
}

Background Position

The background-position property is used to position a background image, with one value for vertical placement and another for horizontal. They can both be set to a length or a percentage of the element's size, and negative values are allowed. There are also some predefined values for this property, including top, center, and bottom for vertical placement; and left, center, and right for horizontal placement.

Example: Try It

body {
    background-image: url("images/flowers.png");
    background-repeat: no-repeat;
    background-position: right top;
}

The Background Shorthand Property

The background property is a shorthand property for setting all the individual background properties, i.e., background-color, background-image, background-repeat, background-attachment and the background-position property at once.

Example: Try It

body {
    background: #f0e68c url("images/gradient.png") no-repeat fixed 250px 25px;
}

When using the background shorthand property the order of the property values should be.

background: color image repeat attachment position;

If the value for an individual background property is missing or not specified while using the shorthand notation, the default value for that property will be used instead, if any.