Part 6: Backgrounds
Backgrounds have many uses in CSS, from tinting the background color of a div to replacing normal HTML text with pre-designed graphics via background-image
. Like the color
property, the background-color
property can take colors as words (red, yellow
), hexadecimal codes (#ccc
, #ffed8b
), rgb values (rgb(128,0,128)
), or rgba values ( rgba(128,0,128, 0.5)
). With rgba, you specify an alpha value (transparency). This will only be recognized by modern browsers; see this 24 ways article for more details. If you’re only specifying a color, use the background-color
property:
div#main {background-color:yellow;}
If you’re using background images, you have a lot more properties and values to specify. It’s generally easiest to use the shorthand background
property, as long as you get the order of the values correct. The following two rules are equivalent:
div#main {
background-color: transparent;
background-attachment: scroll; /* 'fixed' is the other option */
background-repeat: no-repeat;
background-image: url(bg.png);
background-position: 5px 10px;
}
div#main {background: transparent url(bg.png) no-repeat 5px 10px;}
Background images get cropped according to the calculated size of the HTML element to which they’ve been applied: in other words, a large image does not force its corresponding HTML element to expand. If you need your element to be bigger to show the whole background image, just force it to expand by setting an explicit width
and height
on your element:
p#infobox {
background: transparent url(huge-info-icon.png) no-repeat 10px 10px;
width:200px;
height:500px;
}