CSS Background

The background effects for web pages can range from plain colors to attractive images. All having a specific purpose or thought behind them. CSS background properties can be also be used for the same purpose. Depending upon the type of background required, there are various background effects that we’ll discuss in this section.

Background Color

The name itself suggests the plain and simple purpose for this property.
The background-color property can be used to provide different colors to the background.
The background-image: url(“image.png”); takes image path or image url to show in background
The sample code for the same goes like:

The complete example is

The value for the background-color property can be any known CSS color-name, hex code or RGB code.
Color names can be specified like black, white, green, pink, orange, yellow, red etc.
Hex code are six-digit hexadecimal color code followed by # symbol like #000000, #ffffff, #FFFF00 etc.
RGB code is (r,g,b) combination of color between 0 and 255 like (245,222,179) for wheat.

Background Image

Here, instead of color we can have and image file as the web-page background.
The sample code for this is as follows:


Photo by Free Creative Stuff from Pexels

Background Repeat

In order to restrict the background image to repeat in only x or y direction (horizontally or vertically), we use the background-repeat property along with the background image property. The code goes as following

Now the image will repeat in only x direction.

Similar to repeat in y direction use bsckground-repeat:repeat-y;

If you do not want the image to repeat in any direction, the same property can be used like

Background-Position

Used to specify the position of image on the screen. This can be done by the background-position property. The property can be used as follows:


backgroud-position property can have following values

  • Length value like 50px 50px
  • Percentage like 20% 30%
  • Keyword value like left right top bottom center

Background-Attachment

This property is used when you want your background image to be fixed while scrolling the web-page. The sample code:

All these properties can also be used in single line in what is known as the shorthand feature of background property. An example of the same is:

The order of the properties for shorthand is:
Color>Image>Repeat>Attachment>Position