CSS 102

CSS 102

Got something to say?

Share your comments on this topic with other web professionals

In: Articles

By Mark Newhouse

Published on May 4, 2005

Last time, we looked at using CSS to control typography and white space. This time we’ll look at borders and backgrounds.

Before we get started, we need to define some broad categories of elements. Generally speaking, there are two types of elements in HTML: block and inline. There are others, but for this article they can be thought of as subsets of these two broader categories.

The simplest way to think about elements is this: unless otherwise defined in a style sheet, block elements have a width equal to that of the browser window, and are as tall as necessary to contain their content. As the name implies, they reserve a rectangular area—a block—on the page. <hn>, <p> and <div> are block-level tags. Most may contain other block-level elements as well as inline elements.

Inline elements only take up as much area as they need and are contained within block elements. These include <em>, <a>, <img> and <span>. Some inline elements may contain other inline elements, but they may never contain block-level elements.

Whew! You may be wondering why I bothered to type all of that. I have a couple of reasons. First, to have your style sheet work correctly, it needs to apply to a well-formed (X)HTML document. If you mix inline and block-level elements incorrectly, you may have some unexpected results in the way your document is displayed.

Second, this article is covering the use of borders and backgrounds. Block-level elements display their borders and backgrounds in quite a different way than inline elements do. Having an understanding of these distinctions will help you decide how to use them in your design. In fact, we can add borders and/or backgrounds to elements to help us see whether they are block-level or inline elements.

As an example, if we apply a border to ems with a class of “sample1” via the following markup and CSS:

<p>The <em class="sample1">emphasized text
<br /> in this paragraph has a border</em> around it.</p>

.sample1 {
border: 1px solid #333;
}

We get the following result:

The emphasized text
in this paragraph has a border
around it.

I forced a break in the middle of the emphasized text so you can see how the browser handles drawing the border in that situation.

We can apply the same class of “sample1” to a paragraph:

<p class="sample1">In this example the entire paragraph is enclosed in a border.</p>

And here is the result:

In this example the entire paragraph is enclosed in a border.

Borders

You have already seen a shorthand form for specifying the border of an element. Based on the example, you have probably figured out what each part does, and that it applies to all four borders of the element.

The first value in the example refers to the border-width. This value can be set as a length (e.g., 1px), or with the relative values of thin, medium or thick. Relative values are likely to have different renderings in different browsers, but thick will always be thicker than thin.

The width of the border can be set for each border separately by using the properties border-top-width, border-right-width, border-bottom-width and border-left-width. The shorthand property border-width can set them all at once using from one to four values, separated by spaces. The values apply in order to the top, right, bottom, and left borders. If you use fewer than four values they will apply to the borders as follows:

{ border-width: thin } /* thin thin thin thin */
{ border-width: thin thick } /* thin thick thin thick */
{ border-width: thin thick medium } /* thin thick medium thick */

Keep the above in mind as the same pattern applies to shorthand properties for borders as well as padding and margins.

The second value in the example applies to the border-style. This property can take on the following values (as defined by the W3C):

none
No border; the border width is zero.
hidden
Same as ‘none’, except in special cases.
dotted
The border is a series of dots.
dashed
The border is a series of short line segments.
solid
The border is a single line segment.
double
The border is two solid lines. The sum of the two lines and the space between them equals the value of ‘border-width’.
groove
The border looks as though it were carved into the canvas.
ridge
The opposite of ‘groove’: the border looks as though it were coming out of the canvas.
inset
The border makes the box look as though it were embedded in the canvas.
outset
The opposite of ‘inset’: the border makes the box look as though it were coming out of the canvas.

Browsers have a lot of latitude in interpreting borders—some don’t even implement certain styles.

Again, these can be set individually with border-top-style, border-right-style, etc., and can be set all at once with the border-style shorthand property by giving it one to four space-separated values.

The third value sets the border-color. This can be set individually (border-top-color, etc.) or with the border-color shorthand property. The color value may be set as described in the previous article in this series. Additionally, a border may have a color value of transparent. This means that the border is transparent, but it does have whatever width it has been assigned. There are interesting possibilities—check out the CSS House and A Study of Regular Polygons.

Finally, we come to the shorthand property of border. This property sets the three border properties (width, style and color) for all four borders at once. In this shorthand, all four borders receive the same values. If you want different vales, you’ll have to use one of the other border properties.

Backgrounds

In the previous article, we briefly touched on the background property to give a page a background color. But the body of a page is not the only element that can have a background property—any element can have both borders and a background. The background is not limited to color, either—it can also contain an image. The creative use of these properties has led to the beauty and diversity of designs you see on CSS Zen Garden and the CSS Vault.

The default value of any element’s background is transparent. This allows the background of its parent element to show through. If you do not want this to happen, you need to change the background of the element. You can do this by assigning the element a background-color. This property can accept color values in any of the standard formats (hex, abbreviated hex, rgb or keyword). This will apply the color underneath the content, padding and border of the element. Additionally, background-color recognizes transparent (default) and inherit. When inherit is applied to an element, it takes on the background-color of its parent element.

If we go back to our example paragraph and create a class of sample2, we can see how it is applied to inline elements (such as em) and block-level elements (like p).

This CSS:

.sample2 {
background-color: #009;
color: #fff; /* this sets the foreground color for text */
}

combined with this markup:

<p>The <em class="sample2">emphasized text in this paragraph
<br /> should appear in white type against a blue background</em>. Other text should be in the default colors.</p>

Creates the following paragraph:

The emphasized text in this paragraph
should appear in white type against a blue background
. Other text should be in the default colors.

Again, I forced a break so you can see how the browser renders such a case.

If we apply the class to the paragraph:

<p class="sample2">All of the text in this paragraph should appear in white type against a blue background, whether it is <em>emphasized</em> or not.</p>

This is the result:

All of the text in this paragraph should appear in white type against a blue background, whether it is emphasized or not.

Images in Backgrounds

As mentioned above, we are not limited to colors. Elements can also be assigned images for their backgrounds. These can be repeating patterns, subtle gradients, even photographs. We’ll assume your image has been saved in a Web-friendly format (GIF, JPG or PNG). Use the property background-image to set the image. You’ll need to know the location of the image on your server in order to point to it in your CSS. The syntax looks like this:

background-image: url(/files/includes/images/path-to-image.jpg);

You may surround the path with single or double quotes.

The above example uses a rooted path; i.e., the initial slash (/) tells the browser to find the image at this location starting from the root level of the server. You can also use an absolute path (starting with http://) or a relative path. Standards-compliant browsers should look for the image relative to the CSS file.

The image will be rendered on top of any background-color, which means that if the image has any transparency, the color will show through. We can take advantage of this and other background-image properties to create some special effects and save bandwidth vs. the old presentational HTML way of doing things.

Let’s say you want a page that has an image in the top left corner. You also want the content of the page to overlap that image. In other words, the image needs to be in the background, not placed as an inline image.

The old way to do this was to put the background image into the body tag. A big problem with this technique is that the image will tile—repeat itself vertically and horizontally—across the entire page. The typical workaround is to create a huge image with blank space beneath and to the right to create the illusion of a smaller image in the corner. This adds a lot of weight to your page, and the illusion is broken if the content of the page is longer than the image is tall, or the browser window is opened wider than the image.

There is a better way: background-repeat. The default value is repeat, but other values can be set to restrict whether or how to repeat. To make the image tile vertically, set background-repeat to repeat-y. To tile horizontally, set it to repeat-x. This property will also accept a value of inherit, in which case it inherits the value from its parent element. In our example we do not want the image to repeat at all, so we add the following to the rule for the body element:

background-repeat: no-repeat;

Now we have the image in the top left corner of the page.

What if you want that image in the top right corner, middle, or anywhere else on the page? Enter the background-position property. This property allows you to place the background image anywhere you want on the page. You can use keywords, lengths, or percentages to define where you want your image to appear.

We’ll start with the keywords: left and right, which apply to horizontal position; and top and bottom, which apply to vertical position. center can correspond to both horizontal and vertical position.

To position our image at the top right corner of the page, use the following in the rule for the body:

background-position: right top;

With this bit of CSS, no matter how the browser window is resized, the image will stay at the top right corner of the page. If you want the image in the center of the page, you can specify center center. Or you can put it on the bottom of the page with center bottom. (Note: if you have enough page content to force a scroll bar, the image will appear at the bottom of the page, not the bottom of the browser window.)

When you combine this property with background-repeat, you can put a vertical stripe down the right side of the page that will always stay on the right, regardless of how wide the browser window is. Only with CSS!

In addition to the keywords already discussed, you can use lengths, like px, in and cm, as well as percentages. And negative positions are allowed.

So far we have talked about background images in relation to the body element. But any element can have a background image applied to it. In this case, the position of the element is calculated relative to the element’s padding edge. A position of top left will align the top left corner of the image into the top left corner of the element. A position of bottom right will align the lower right corner of the image with the bottom right corner of the element. This corresponds to 0% 0% for top left and 100% 100% for bottom right. As you might guess, 50% 50% is the same as center center.

In fact, percentage-based positions are calculated differently than length-based positions. If you apply a position of 20% 32%, the browser should calculate the point 20% across and 32% down from the top left corner of the element, and place the pixel that is 20% across and 32% down from the top left corner of the image there when it draws the image. This means that the center of the image will be at the center of the page when you specify 50% 50% (or center center). Lengths place the top left corner of the image at the lengths you specify (relative to the top left corner of the element).

Above I indicated that you can place an image at the bottom of a page, but if you have enough content you may need to scroll to see it. With the background-attachment property, you can ensure that it will always be seen, right at the bottom of the browser window—no matter how much you scroll.

There are two values (three if you count inherit) that this property will accept: scroll and fixed. If you want the image to scroll with the page, use scroll. The image will stay “attached” to the page, regardless of how long it gets. If you want the image to stay in place and not scroll, use fixed. This has the effect of attaching the image to the browser window so that it will not move, no matter how much you scroll.

Putting it All Together

As with the other properties we looked at in this article, there is a shorthand version that combines all the properties: background. This property combines background-color, background-image, background-repeat, background-attachment and background-position into a single property. When used in a style sheet, background sets all of the background properties to their default values and then applies the new values that you include. If you leave one or more values out of the declaration, it will take on its default value, even if you have previously set that value in the style sheet. For example, this rule:

div#content {
background-color: #aaa;
background: url(/files/includes/images/path-to-img.jpg) no-repeat;
}

will result in a non-repeating image placed at the top left corner of the div. The background color of the div will be whatever background color its parent element has, not #aaa. This is because it was reset from #aaa to the default value of transparent when no color value was given to the background property. Likewise, since no position values were given, it will default to the top left corner of the div, and will scroll with the page.

Conclusion

I’ve just covered the basics of borders and backgrounds. Armed with this new knowledge and some experimentation, you can now create some very interesting effects.

Find inspiration in techniques pioneered by Eric Meyer:

Related Topics: Web Design, CSS, Basics

Mark Newhouse is the Web Designer for the National Optical Astronomy Observatory where he is fully aware of the unrealized potential of CSS. He enjoys the challenge of creating sites that use standards, look good, and work across browsers and platforms. Including Netscape 4 on Unix.