background-image (CSS property)

Description

This property sets the background image of an element via the specified URI. The image is placed on top of the background-color, and if the image is opaque, the background-color will not be visible beneath it. When you’re setting a background-image, also set a background-color, where possible, in case the image is unavailable.

The background of an element is the area covered by the width and height of that element (whether those dimensions are set explicitly, or the content dictates them); it also includes the area covered by padding and borders. A background-color (or background-image) that’s applied to an element will appear beneath the foreground content of that element, and the area covered by the padding and border properties for the element. This coverage area is evident where an element has transparent (or dotted or dashed) borders, and the background is seen beneath the borders (or between the dots). Note that Internet Explorer versions up to and including 6 don’t support transparent borders.

Some area of the element in question must be visible so that the background-image can show through. If the element has no intrinsic height (either defined by its content or dimensions), the background won’t have any space in which to display. If an element contains only floated children which haven’t been cleared—see clear—again, the background won’t display, since the element’s height will be zero.

By default, the background-image is placed at the top-left (background-position) of the element; it’s repeated along the x and y axes (background-repeat) and will scroll with the document. These are the default settings that apply if you haven’t explicitly set any others, and can be adjusted with the other background properties. Refer to the other relevant stuff below for methods you can use to position and control the image.

Example

This style rule assigns a background
image to the element with ID "example" :

#example {
  background-image:
  ➥    url(images/bg.gif);
}

Value

A URI value specifies a location at which the image can be found.

The value none ensures that no background-image will be displayed; this is the default setting, so you don’t need to define it explicitly unless you want to override previous background-image declarations.

The value inherit would cause the element to inherit the background-image of its parent. This approach would not normally be taken, as the element’s inherited background image would most likely overlap the parent’s image. In most cases, the parent’s background-image will be visible through the element’s transparent background unless another background-image or background-color has been set.

Learn HTML5 Online

Get all SitePoint books and courses with a Learnable membership. Start building future-proof websites that are faster, more powerful, and easier to maintain.

No Reader comments

Comments on this post are closed.