CSS Properties

Page 5

Background Properties

With old-school HTML, we used to use properties on the BODY tag to give a page a background. With CSS, we can give backgrounds to any element.

background-color

Using background-color, you can give a background color to any element. We'll demonstrate with an anchor tag.

Example

CSS

a {background-color:#000000; color:#ffffff;}

Markup

<body>
<p>I like <a href="http://technorati.com">Technorati</a>. I think it's neat.</p>
</body>

Display

I like Technorati. I think it's neat.

background-image, background-position, and background-repeat

You can also assign an image to be an element's background. This can do anything from creating wallpapers for your page to substituting for an img tag. You give the background-image property your image's url, and you're good to go. But first, you may want to specify whether or not the image is supposed to repeat, since with many browsers the default is 'repeat'. Valid values for the background-repeat property are repeat, no-repeat, repeat-x, and repeat-y. If you want only one copy of your image, use no-repeat. To repeat horizontally, use repeat-x, and to repeat vertically, use repeat-y.

The background-position property tells the image where within the element you're styling it should appear. The property accepts paired values, either percentages or lengths. The first tells the horizontal, the second the vertical position. So a value of '50% 0%' would be centered at the top, and '8px 100px' would be eight pixels to the right and 100 pixels below the upper-left corner.

Here's an example using background-image and the text-indent property from earlier in this article.

Example

CSS

p {text-indent:20px; background-image:url("smile.gif"); background-repeat:no-repeat; }

Markup

<body>
<p>Let freedom ring. And when this happens, and when we allow freedom ring - when we let it ring from every village and every hamlet, from every state and every city, we will be able to speed up that day when all of God's children - black men and white men, Jews and Gentiles, Protestants and Catholics - will be able to join hands and sing in the words of the old Negro spiritual: "Free at last! Free at last! Thank God Almighty, we are free at last!"</p>
</body>

Display

Let freedom ring. And when this happens, and when we allow freedom ring - when we let it ring from every village and every hamlet, from every state and every city, we will be able to speed up that day when all of God's children - black men and white men, Jews and Gentiles, Protestants and Catholics - will be able to join hands and sing in the words of the old Negro spiritual: "Free at last! Free at last! Thank God Almighty, we are free at last!"