Last updated on

The background property of CSS allows you to control the background of any element. For instance to change the background of an entire page to a light gray, you could do:

html {
   background: #ccc; 
}

The value “#CCC” is known as a hex code. It represents a color value. There are a number of ways to get hex codes. Users of Photoshop might be familiar with it’s color picker.

Note the hex code in the lower middle.

But hex codes aren’t the only way to declare color. There are also named colors. For instance:

#page-wrap { background: white; }
footer { background: black; }
button.warning { background: red; }

RGB / RGBa / HSL / HSLa are yet another way to declare colors:

#page-wrap {
  background: rgba(0, 0, 0, 0.8); /* 80% Black */
}
.widget {
  background: hsla(170, 50%, 45%, 1);
}

So far we’ve only talked about colors, but backgrounds can be images too.

body {
  background: url(texture.jpg);
}

Using the url() value you can supply a file path to an image you want to use as the background for that element. By default, that image will repeat. To prevent it from repeating, you’d add an extra property.

body {
  background: url(pretty-flower.jpg) no-repeat;
}

What is actually happening there is that background is actually a shorthand version of many properties put together. What is happening above is really this, shortened:

body {
  background-image: url(pretty-flower.jpg);
  background-repeat: no-repeat;
}

But it’s important to note that the short hand also resets values that you don’t specify. Notice we didn’t indicate any color, so the color is automatically set to transparent, the default value for background-color.

The complete list of background-properties that compile into background are:

background-attachment: scroll, fixed
background-color: transparent, hex, named, rgba(), hsla()
background-image: none, url() or gradient
background-position: top, left, bottom, right or specific values e.g. 20px 20px
background-repeat: repeat, no-repeat

And there are a few more that can be used but not included in the shorthand:

background-size: auto, contain, cover, or specific values e.g. 20px 20px
background-origin: padding-box, border-box, content-box
background-clip: border-box, padding-box, content-box

Browser Support

Support varies amongst the different specific properties. Setting a background color with a hex code is support in everything. Using background-size: cover; is only supported in Safari 3+, Chrome any, IE 9+, Opera 10+ and Firefox 3.6+. RGBa is similar in support but goes back to Firefox 3.0.

Chrome Safari Firefox Opera IE Android iOS
Works Works Works Works Works Works Works

Leave a Reply

Your email address will not be published. Required fields are marked *