CSS Background

CSS background properties are used to define background styles for the elements.

Background Properties

The CSS provide several properties for styling the background of an element, like:background-color, background-image, background-repeat, background-attachment andbackground-position. The following section will describe you how to use these properties to set the different styles for the backgrounds one by one.

Background Color

The background-color property is used to set the background color of an element.

The example below demonstrates, how to set the background color of a web page.

Colors in CSS most often specified by the following methods:

  • a HEX value – like “#ff0000”
  • an RGB value – like “rgb(255,0,0)”
  • a color name – like “red”

Look at CSS Color Names for a complete list of possible color names.


Background Image

The background-image property set an image as a background of an HTML element.

See the example below which demonstrates how to set the background image for a page.

Background Repeat

By default the background-image property repeats an image both horizontally and vertically.

By using background-repeat property you can control how a background image is tiled in the background of an html element. You can set a background image repeat vertically (y-axis), horizontally (x-axis), in both directions, or in neither direction.

See the example below which demonstrates how to set the gradient background for a web page by repeating the sliced image horizontally.

Background Attachment

The background-attachment property determines whether the background image is fixed with regard to the viewport or scrolls along with the containing block.

Background Position

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

If no background-position has been specified, the image is placed at the default top-left position of the element i.e. at (0,0). See the example below:

In the following example, the background image is positioned at top-right corner and the position of the image is specified by the background-position property.

The Background Shorthand Property

As you can see from the examples above, there are many properties to consider when dealing with the backgrounds. It is also possible to specify all these properties in one single property, to shorten the code. This is called a 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 background-position) at once. For example:

Using the shorthand notation the above example can be written as:

 

Loading