CSS - Adding a touch of style

Don't you want your pages to just glow?

Forget the cheesy filter above. This is a short guide to styling your Web pages. It will show you how to use W3C's Cascading Style Sheets language (CSS) as well as alternatives using earlier HTML (versions before HTML4). Hopefully, we can avoid many of the problems caused by differences between brands and versions of browsers.

Getting started

There are four different implementations of styles that may be used with Web content:

Both linked and imported styles use external text documents (style rules) to allow reference to a standard set of rules.

The implementation of the style will use rules with declarations, values, properties, and selectors, setup using minor differences in syntax. To get an idea of the range and use of some of these 100+ capabilities, let's start with setting the color of the text and the background. You can do this by using the STYLE element to set style properties for the document's tags:

<style type="text/css">
  body { color: black; background: white; }
</style>

The rules between the <style> and </style> are written in special notation for style rules. Each rule starts with a selector (HTML tag name, or CLASS) followed by a list of style properties or values bracketed by {  }, which is then designated a declaration. Multiple declarations may be included in the brackets, separated by semicolons. In this example, the rule matches the body tag. As you will see, the body tag provides the basis for setting the overall look and feel of your Web page.

Each style property starts with the property's name, then a colon and lastly the value for this property. When there is more than one style property in the list, you need to use a semicolon between each of them to delimit one property from the next. In this example, there are two properties - "color" which sets the color of the text, and "background" which sets the color of the page background. The semicolon after the last property is optional.

Colors can be given as names or as numerical values, for instance rgb(255, 204, 204) which is a fleshy pink. The 3 numbers correspond to red, green and blue respectively in the range 0 to 255. You can also use a hexadecimal notation, the same color can also be written as #ffcccc. More details on color are discussed in a later section.

Note that the style element must be placed in the document's head along with the title element. It should not be placed within the body, unless the style rules are to apply only to the instance where it appears in the code.

Using styles inline

You may create and apply a style within your code (inline) by adding the style attribute after the element tag, with rules in parentheses. For example:

<h3 style="color: red; background: yellow;">

Using embedded styles

Embedding the styles within the HEAD section will create rules that apply to the page only.
<style type="text/css">
<!--
  body { color: black; background: white; }
//-->
</style>

Linking to a separate style sheet

If you plan to use the same styles for several Web pages it is worth considering using a separate style sheet which you then link from each page. Using a text editor, create a list of styles as if you were embedding between the <style> container (all the style rules listed). Save the style rules file as a text type with a name extension .css. You may then reference the style sheet (style.css in this example) within the head section of a page that you want to apply the style by including the following line:

<link rel="stylesheet" href="style.css" type="text/css">

The LINK tag should be placed in the document's head. The rel attribute must be set to the value "stylesheet" to allow the browser to recognize that the href attribute gives the Web address (URL) for your style sheet.

A similar link to the style sheet is provided with the import tag used in the <style> container in the <head>, but this implementation is supported only by MS Internet Explorer.

<head>
<style>
<!--
@import: url(style.css);
-->
</style>

Note the use of HTML comment tags <!-- . . . -->to force sytle-unaware browsers to ignore the style definitions.

Units

With CSS, you may specify the length or size of some properties in units, rather than the normal HTML value. These units may represent a percentage of the page (%), or physical sizes such as below.

Unit

Definition

em m, the height or width of letter m
ex x, the height or width of letter x
px pixel, a screen dot (picture element)
pt point, 1 pt = 1/72 inch
in inch, 1 in = 2.54 cm
cm centimeter
mm millimeter
pc pica, 1 pc = 12 pt

Setting the page margins

Web pages may look nicer with bigger margins. You can set the left and right margins with the "margin-left" and "margin-right" properties, e.g.,

<style type="text/css">
  body { margin-left: 10%; margin-right: 10%; }
</style>

This sets both margins to 10% of the window width, and the margins will scale when you resize the browser window.

Setting left and right indents

To make headings a little more distinctive, you can make them start within the margin set for the body, e.g.,

<style type="text/css">
  body { margin-left: 10%; margin-right: 10%; }
  h1 { margin-left: -8%;}
  h2,h3,h4,h5,h6 { margin-left: -4%; }
</style>

This example has three style rules. One for the body, one for h1 (used for the most important headings) and one for the rest of the headings (h2, h3, h4, h5 and h6). The margins for the headings are additive to the margins for the body. Negative values are used to move the start of the headings to the left of the margin set for the body.

In the following sections, the examples of particular style rules will need to be placed within the style element in the document's head (if present) or in a linked style sheet.

Controlling the white space above and below

Browsers do a fair job of providing white space above and below headings and paragraphs, etc. You may wish to take control of this yourself when you want a lot of white space before a particular heading or paragraph, or when you need precise control for the general spacings.

The "margin-top" property specifies the space above and the "margin-below" specifies the space below. To set these for all h2 headings you can write:

h2 { margin-top: 8em; margin-bottom: 3em; }

The em is a very useful unit as it scales with the size of the font. One em is the height of the capital letter "M" in the particular font family. By using the em unit,  you can preserve the general look of the Web page independently of the font size. This may be safer than alternatives such as pixels or points, which can cause problems for users who set systems up with large fonts to read the text.

Points (72 points per inch) are commonly used in word processing packages, e.g., 10pt text. Unfortunately the same point size is rendered differently on different browsers. What works fine for one browser may be illegible on another! Sticking with the em can avoid these problems.

Class Selector

To specify the space above a particular heading, you should create a named style for the heading. You do this with the class attribute in the markup, e.g.,

<h2 class="subsection">Getting started</h2>

The style rule is then written as:

h2.subsection { margin-top: 8em; margin-bottom: 3em; }

The rule starts with the tag name, a dot and then the value of the class attribute. Be careful to avoid placing a space before or after the dot. If you do, the rule won't work. There are other ways to set the styles for a particular element but the class attribute is the most flexible.

When a heading is followed by a paragraph, the value for margin-bottom for the heading isn't added to the value for margin-top for the paragraph. Instead, the maximum of the two values is used for the spacing between the heading and paragraph. This subtlety applies to margin-top and margin-bottom regardless of which tags are involved.

First-line indent

Sometimes you may want to indent the first line of each paragraph. The following style rule emulates the traditional way paragraphs are rendered in novels:

p { text-indent: 2em; margin-top: 0; margin-bottom: 0; }

It indents the first line of each paragraph by 2 em's and suppresses the inter-paragraph spacing.

Controlling the font

This section explains how to set the font and size, and how to add italic, bold and other styles.

Font styles

The most common styles are to place text in italic or bold. Most browsers render the em tag in italic and the strong tag in bold. Let's assume you instead want em to appear in bold italic and strong in bold uppercase:

em { font-style: italic; font-weight: bold; }
strong { text-transform: uppercase;  font-weight: bold; }

If you feel so inclined, you can fold headings to lower case as follows:

h2 { text-transform: lowercase; }

Setting the font size

Most browsers use a larger font size for more important headings. If you override the default size, you run the risk of making the text too small to be legible, particularly if you use points. You are therefore recommended to specify font sizes in relative terms.

This example sets heading sizes in percentages relative to the size used for normal text.

h1 { font-size: 200%; }
h2 { font-size: 150%; }
h3 { font-size: 100%; }

Setting the font family

It is likely that your favorite font won't be available on all browsers. To get around this, you are allowed to list several fonts in preference order. There is a short list of generic font names which are garanteed to be available, so you are recommended to end your list with one of these: serif, sans-serif, cursive, fantasy, or monospace, for instance:

body { font-family: Verdana, sans-serif; }
h1,h2 { font-family: Garamond, Times New Roman, serif; }

In this example, important headings would preferably be shown in Garamond, failing that in Times New Roman, and if that is unavailable in the browsers default serif font. Paragraph text would appear in Verdana or if that is unavailable in the browser's default sans-serif font.

The legibility of different fonts generally depends more on the height of lower case letters than on the font size itself. Fonts like Verdana are much more legible than ones like Times New Roman and are therefore recommended for paragraph text.

Drop Caps

This is an example of how to produce the effect of drop caps, without running afoul of browser compatibity problems. It relies on you placing the first letter of the paragraph in a span element. In future, the need for the span element should disappear as browsers implement the CSS first-letter mechanism.

This is an example
of how to produce the effect of drop caps, without ...

The style rule used to achieve this effect is:

  .dropcap {
     float: left;
     font: bold 1.4em "Times New Roman", serif;
     color: rgb(51, 0, 102);
     background: rgb(255, 255, 153;)
  }

Defining block areas with the div tag

Originally meant as a simple tool to group page elements, the DIV tag defines a block or division that when combined with Cascading Style Sheet (CSS) properties, may provide designers additional flexibility and control over layout such as:

Designers use the div to create complex page layouts without using tables. Unfortunately, as layouts become more complex, browser compatibility problems increase.

Adding borders and backgrounds

You can easily add a border around a heading, list, paragraph or a group of these enclosed with a div element. For instance:

div.box { border: solid; border-width: thin; }

which can be used with markup such as:

<div class="box">
The content within this DIV element will be enclosed
in a box with a thin line around it.
</div>

There are a limited choice of border types: dotted, dashed, solid, double, groove, ridge, inset and outset. The border-width property sets the width. Its values include thin, medium and thick as well as a specified width e.g., 0.1em. The border-color property allows you to set the color.

A nice effect is to paint the background of the box with a solid color or with a tiled image. To do this you use the background property. You can fill the box enclosing a div as follows:

  div.color {
    background: rgb(204,204,255);
    padding: 0.5em;
    border: none;
  }
  

Without an explicit definition for border property some browsers (Netscape) will only paint the background color under each character. The padding property introduces some space between the edges of the colored region and the text it contains.

You can set different values for padding on the left, top, right and bottom sides with the padding-left, padding-top, padding-right and padding-bottom properties, e.g., padding-left: 1em.

Suppose you only want borders on some of the sides. You can control the border properties for each of the sides independently using the border-left, border-top, border-right and border-bottom family of properties together with the appropriate suffix: style, width or color, for example:

  p.changed {
             padding-left: 0.2em;
             border-left: solid;
             border-right: none;
             border-top: none;
             border-bottom: none;
             border-left-width: thin;
             border-color: red;
            }

which sets a red border down the left hand side only of any paragraph with the class "changed".

More CLASS

A class may be defined in the embedded style,

<style type="text/css">
  .important { background: red; }
</style>

and then may be used as a property like in the above examples, or may be used inline.

<h1 class="important"> Example </h1>

When using some WYSIWYG-like HTML editing tools like Microsoft FrontPage, the classes that you defined will be available as a "style" to be applied to any paragraph. This is an easy way to apply rules to your content.

An ID is similar to a CLASS

An ID may be defined in the embedded style,

<style type="text/css">
  #important { background: red; }
</style>

and then may be also used as a property like in the above examples, or may be used inline. However, only one element can have the ID value, so classes are more versatile.

<h1 id="important"> Example </h1>

Microsoft FrontPage does not show this ID within the "style" drop-down box, so classes are easier to apply when using this editor.

What about browsers that don't support CSS?

Older browsers, that is to say before Netscape 4.0 and Internet Explorer 4.0, either don't support CSS at all or do so inconsistently. For these browsers you can still control the style by using HTML3.2 tags and attributes. None of the current browsers support all of the recommended W3C (there is a CSS1 and CSS2) standards, but Microsoft has done a much better job of compliance. Eric Meyer at WebReview publishes an excellent guide to browser compatibility. Hopefully IE5 and NS5 will be even better implementations for this most important of the Dynamic HTML features. As you build your pages, you may want to use the CSS validation services of the W3C to help identify problems before you publish.

Setting the color and background

You can set the color using the BODY tag. The following example sets the background color to white and the text color to black:

<body bgcolor="white" text="black">

The BODY element should be placed before the visible content of the Web page, e.g., before the first heading. You can also control the color of hypertext links. There are three attributes for this:

Here is an example that sets all three:

<body bgcolor="white" text="black"
  link="navy" vlink="maroon" alink="red">

You can also get the browser to tile the page background with an image using the background attribute to specify the Web address for the image, e.g.,

<body bgcolor="white" background="texture.jpeg" text="black"
  link="navy" vlink="maroon" alink="red">

It is a good idea to specify a background color using the bgcolor attribute in case the browser is unable to render the image. You should check that the colors you have chosen don't cause legibility problems. As an extreme case consider the following:

<body bgcolor="black">

Most browsers will render text in black by default. The end result is that the page will be shown with black text on a black background! Lots of people suffer from one form of color blindness or another, for example olive green may appear brown to some people.

A separate problem appears when you try to print the Web page. Many browsers will ignore the background color, but will obey the text color. Setting the text to white will often result in a blank page when printed, so the following is not recommended:

<body bgcolor="black" text="white">

You can also use the bgcolor attribute on table cells, e.g.,

<table border="0" cellpadding="5">
 <tr>
  <td bgcolor="yellow">colored table cell</td>
 </tr>
</table>

Tables can be used for a variety of layout effects and have been widely exploited for this. In the future this role is likely to be supplanted by style sheets, which make it practical to achieve precise layout with less effort.

Named colors

The standard set of color names is: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. These 16 colors are defined in HTML 3.2 and 4.0 and correspond to the basic VGA set on PCs. Most browsers accept a wider set of color names but use of these is not recommended since there is no agreement on color names, so the indigo you specified may not appear.

Hexadecimal color values

Values like "#FF9999" represent colors as hexadecimal numbers for red, green and blue. The first two characters following the # give the number for red, the next two for green and the last two for blue. These numbers are always in the range 0 to 255 decimal (00 to ff hexadecimal). If you know the values in decimal, you can convert to hexadecimal using a calculator, like the one that comes as part of Microsoft Windows.

Browser safe colors

Many older color systems can only show up to 256 colors at a time. To cope with this, browsers make do with colors from a fixed palette of 216, using the additional 40 colors for the operating system color requirements. The effect of trying to show a color that is not part of the available palette appears as dithering, often visible as a speckling of colors as the browser tries to approximate the true color at any point in the image.

Most browsers use the same so called "browser safe" palette. This uses 6 evenly spaced gradations in red, green and blue and their combinations. If you select image colors from this palette, you can avoid the speckling effect. This is particularly useful for background areas of images.

all colors in the browser safe palette

These are constructed from colors where red, green and blue are restricted to the values:

RGB 00 51 102 153 204 255
Hex 00 33 66 99 CC FF

The page background uses the nearest color in the palette. If you set the page background to a color which isn't in the browser safe palette, you run the risk that the background will have different colors depending on whether the computer is using indexed or true-color.

How do you find browser safe colors?

Just when I was feeling confident about choosing and using "browser safe" colors, I saw the partial specification for a set of named colors for dhtml that themselves do not comply with the 216 discussed above. Netscape does not even truly render some of those in the spec. I must do more digging to find what really is the best choice for HTML4 standards. In the interim, I will stick with the 216 colors in the triplet combos of hex 00,33,...cc,ff.

Setting the font, its size and color

The FONT tag can be used to select the font, to set its size and the color. This example just sets the color:

This sentence has a <font color="yellow">word</font> in yellow.

The face attribute is used to set the font. It takes a list of fonts in preference order, e.g.,

<font face="Garamond, Times New Roman, serif">some text ...</font>

The size attribute can be used to select the font size as a number from 1 to 6. If you place a - or + sign before the number it is interpreted as a relative value. Use size="+1" when you want to use the next larger font size and size="-1" when you want to use the next smaller font size, e.g.,

<font size="+1" color="maroon"
  face="Garamond, Times New Roman">some text ...</font>

Now introduce yourself to CSS

Control of content using HTML3.2 tags requires intervention at each section of the code, and is difficult to modify or setup as a template. As creative Web developers, you will want to begin using CSS in content when appropriate for your audience (what browsers must be supported?). For a more detailed explanation, W3Schools CSS tutorial and reference , provides an in-depth look at CSS including an interactive example code trial. Another useful tutorial is found at Webmonkey.

Eric Meyer is a designer and innovator, and publishes some great books and websites demonstrating css. the css edge is one of my favorites. And if you want to see some visual examples to help get past the table layout habit, visit csseasy.com.

Some specifications for CSS1 styles are listed for reference as a help for your to start controlling more of the visual appearance of pages. Or a CSS list based on MSDN and WC3 CSS reference is also available at JavaScript Kit. And a great resource list for all things css is Holy CSS Zeldman!.