Home /CSS/Background

Background

Styling the CSS Background Property

Setting the CSS background property of an HTML element is easy! It provides one of the greatest changes you can do in styling with minimal effort. With only five properties, this tutorial is relatively simple.

Common Properties:

  • background-color – sets the background color
  • background-image – links to an image and displays it in the background
  • background-repeat – determines how to tile or repeat the image for larger HTML elements
  • background-position – sets the background position

Example

<style type="text/css">
div.special {
  background-color: #090;
  background-image: url('/images/smiley3.gif');
  background-repeat: repeat-x;
  background-position: left bottom;
}
</style>

<div class="special">
  line 1
  <br />
  line 2
</div>

Result

line 1
line 2

Explanation

We have a div with the class of special that contains a few line breaks and some text to make it taller. In our CSS, we use background-color set to #090 (green), which becomes the color of the special div’s background.

Next, we set the background-image to a URL referencing '/images/smiley3.gif'. The background image requires url(), where your link will go between the single quotes. Quick note: it might seem like a conflict to set both a background color and a background image, but the background color acts as a fallback for areas not covered by the background image.

The background-repeat property defaults to repeat, which commands the browser to repeat the image both horizontally and vertically. You must override this property if you expect anything different, as shown by setting background-repeat to repeat-x for horizontal repetition only.

Finally, the background-position property allows you to position the background wherever you would like. This property is typically useful only if the image is smaller than the HTML element. In this example, it was used with a repeating background image for illustrative purposes.