CSS3 Background

Since css2, we are using background images. There was a limiitation( in css2 ) that only one image can be used in a single element. Another limitation was that background images with background-repeat:no-repeat are for fixed elements only. For liquid elements like body, background images are full only if screen resolution and image size are same. But CSS3 introduced background size property to overcome this issue.

Various Background Properties

Background Property Value
Background-color color of background
Background-image url of background image
Background-repeat repeat (default), no-repeat, repeat-x, repeat
Background-position position of background image, first value for x-axis and second for y-axis, exp, left top, center top, 10px 30px, 20% 50%, etc
Background-attachment scroll(default), fixed
Background-size auto( default), cover, contains Introduced in css3
Background-origin padding-box(default), content-box and border-box Introduced in css3

Background Size

CSS3 Background size property allow us to specity size of background image. Default size for a background image is actual size of image. We can set Background size of image in px, %, cover and contain.

Background Size Values

Background sizepx100px 50pxwidth of background-image is 100px an heigth is 50px
Background size%100% 50%width of background-image is 100% of parent element an heigth is 50% of parent element
Background sizecovercover autoon x axis image will cover full width, and height will be auto adjusted
Background sizecontaincontain auto scale image in x axis with same aspect ratio.

Background Origin

Background Origin property specify background area for background image, this could be border-box, contain-box and padding-box.

Background origin will not work if background-attachment is fixed.

Background Origin Values

Background-origin:border-boxbackground-image will extands till outside edge of border.
Background-origin:contain-boxbackground-image will extands only till padding, not border.
Background-origin:padding-boxbackground image will cover only content area of background.

Multiple Backgrounds

Multiple backgrounds were introduced in css3. Using this property, when can add Multiple backgrounds images with color, and multiple background gradients in a single element. Hera are some examples of how to use multiple background images.

Multiple background images example

        background:url(x.png), url(y.png), url(z.png), #ccc;

<div class="box"></div>


Multiple background images with shorthand

        background:url(x.png) repeat-x left top,
        url(y.png) repeat-y left top, 
        url(z.png) no-repeat center top, 

<div class="box"></div>


For Old Firefox, use -webkit-, for chrome and safari, use -webkit- and for Internet explorer IE 9, use -ms- prefix.