Description
This property sets the background-color
of an element; it’s good practice to specify a foreground color (color
) at the same time, to ensure that conflicts don’t arise with colors or backgrounds that are defined elsewhere.
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 if the background-color
is to show through. If the element has no intrinsic height (defined either by its content or its dimensions), the background will not be seen. If an element contains only floated children which haven’t been cleared then again the background won’t show, as the element’s height will be zero.
The background
of an element isn’t inherited by its children as is commonly thought, it’ just that the background
will be visible through the child element’s background as the default value is transparent
.
Example
This style rule assigns a white background (#fff
) to the element with ID "example"
:
#example{
background-color: #fff;
}
Value
color
takes any valid CSS color value or color keyword.
The keyword transparent
sets the background-color
to be transparent. This value ensures that the content of any element that’s beneath the current element will be visible through the transparent background. The default for background-color
is transparent
, so there is no need to specify this value unless you’re overwriting previous definitions.
Color values can be represented in several different ways in CSS (e.g RGBA color values), and the topic is covered in the CSS Concepts section.
Tom is the product manager, data analyst and office barista at SitePoint.