Styling Backgrounds With CSS

In this lesson you will learn how to apply backgrounds to your webpages using CSS.

Background-Color Property

The background-color property is one of the most frequently used in CSS. Using this property a background color can be set.

Colors are specified in one of three ways; It can be specified by color name ( example white ), by a unique hexadecimal number ( example #FFFFFF) or by an rgb (red, green, blue) value [ example rgb( 255,255,255 ) ].

body
{
    background-color: #D8D8D8;
}

The above hexadecimal value corresponds to a shade of purple. You can also apply a background to different elements within a div tag. Try using different colors to see the corresponding effect.

Background-Image Property

This property in CSS is used to apply a background image to a page. If the image is big enough it will cover the entire page, however if the image is too small it will repeat until the entire background is covered.

body
{
    background-image: url('background.png');
}

The url section specifies the location, name and type of image. It is important that this is correctly specified otherwise the background image will not be displayed.

Background-Repeat Property

The background-repeat property is used closely with the background-image property. It specifies if an image should be repeated vertically, horizontally or none at all.

The values of this property are repeat-y and repeat-x. The repeat-y value corresponds to he y-axis (vertical) and the repeat-x value corresponds to the x-axis (horizontal).

If no background-repeat property is set, the image by default repeats both vertically and horizontally. To not have an image repeat the value no-repeat should be used.

body
{
    background-image: url('background.png');
    background-repeat: repeat-y;
}

Background-Position Property

The background-position property allows the positioning of a background. Two of the most frequently used ways of setting the value of this property is by percentage value ( example 50 % 50% ) and stating the position ( example top right ).

By default, any image you apply is positioned in the top left corner.

Possible positions include: top left, top center, top right, bottom left, bottom center, bottom right, center left, center right and center center

#bg
{
   background-position: top-right;
}
#bg-second
{
background-position: 80% 40%;
}

Background-Attachment Property

The background-attachment property is used to determine whether a background should scroll or remain in a fixed position. The value of the background-attachment property can be fixed or static.

body
{
    background-image: url('background.jpg');
    background-attachment: fixed;
}