CSS Background : Styling



CSS Background properties deals with styling of background color,position and image of an element. Background CSS properties are used for background effects -

background Sets all the background properties in one declaration
background-attachment Sets whether a background image is fixed or scrolls with the rest of the page
background-color Sets the background color of an element
background-image Sets the background image for an element
background-position Sets the starting position of a background image
background-repeat Sets how a background image will be repeated

Property #1 : Background Color

The background-color property specifies the background color of an element. Syntax of this property is as follow -

body {
background-color:#336699;
}

CSS Color can be written in 3 following ways -

HEX Value like “#ff0000”
RGB Value like “rgb(255,0,0)”
Color Name like “red”

Property #2 : Background Image

The background-image property specifies an image to use as the background of an element. Image repeats itself in order to cover complete area of an element.

Syntax of the property is below -

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

In the above example complete background of the body is filled with texture.gif image.
Complete Background - CSS
Above image is repeated itself along X-direction and also along Y-direction.

Property #3 : Background Repeat

In order to make image repeated only in X-direction or Horizontal Direction we use -

body {
background-image:url('texture.gif');
background-repeat:repeat-x;
}

By default, the background-image property repeats an image both horizontally and vertically.
Similarly to repeat image only in Vertical direction we can use following syntax -

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

Property #4 : Background Position

When we set any image as background image and we want that image should not disturb the text then we use background-position property to set exact position of an background image -

body {
background-image:url('flower.png');
background-repeat:no-repeat;
background-position:right top;
}

below is the sample output of the above property -
background-position

Property #5 : Background - Shorthand property

Above all properties can be combined together in one single property. Combined property is called as shorthand property

body {
    background:#ffffff url('flower.png') no-repeat right top;
}

When we are using shorthand property the order of the property values should be like this -

1. background-color
2. background-image
3. background-repeat
4. background-attachment
5. background-position

It is not necessary to write or specify all the properties but all the present properties should be in order.