Formatting HTML Documents Using Style Sheets

Version 3.0 - May 5, 2007

I. What are styles and Cascading Style Sheets (CSS)?

Styles are rules that control the format and display of the contents of web pages.  They can control fonts, backgrounds, colors, borders, position, size, spacing, and visibility of various page elements.  Aside from providing more control of presentation elements than HTML tags provide alone, styles facilitate the separation of page content from presentation.  With styles, it is possible to make a page look very different without touching the HTML code or the content!

II. Style Sheet Rules, Structure, and Syntax

Style rules are always associated with a selector that determines which tag(s) the rule applies to, and a declaration, which lists various style attributes and values.  When a style rule is expressed as the value of the "style" attribute of an HTML tag, it is known as an inline style, the implied selector is that tag, and the style applies to that one tag.

Style sheets consist of a series of style sheet rules (and optional comments).  Within style sheets, each declaration is enclosed in braces, and the selector is outside of the braces.

Here are two simple style sheet rules, with comments.  In these two examples, the selector is a tag name, indicating that the style declaration will apply to every instance of the tag that follows the style rules. Note that whitespace (in this case, a carriage return or end-of-line) is all that is needed to separate rules from each other.

/* Make table headings brown and a little smaller than regular text /*
th {color:brown;size:90%;}
p {text-indent:2em;} /* Indent the first line of paragraphs */

Multiple Selectors can be used in a single rule by separating them with commas, e.g.

h1,h2,h3 {color:green;}

is the same as:

h1 {color:green;}
h2 {color:green;}
h3 {color:green;}

III. Classes, or named styles

Class definitions allow you to save style definitions and apply them to specific tags or elements. When the name given in a style rule selector begins with a period, the name is a class name. For example, the style rules

.important {color:darkred;font-weight:bold;} /* Important messages are dark red, bold */
p.notsoimportant {color:pink;}

define

  1. a class named "important" that can be applied to any HTML elements through the "class" attribute of specific HTML tags, and
  2. And a class called "notsoimportant" that can be used only in <p> tags.

With these two rules in place, the HTML code

<p class=important>Pay attention to these messages...</p>
<p class=notsoimportant>Except this one</p>

Would look like this

Pay attention to these messages...

Except this one (which is pink when displayed on the screen!?!)

IV. Placing Style Rules in Your Document:

There are three places where style rules can be placed in an HTML document:

  1. In-line Styles
    A style defined through the "style" attribute of an HTML tag is an "in-line" style. In-line styles are used when the style will be applied to just a few HTML elements, so a global style definition is not be needed.

    <body style="color:brown; background-color:linen;">
    <h3 style="color:red;"> <!-- Make this one heading red -->

    An in-line style attribute applies only to the one element where is it specified (and possible elements contained within that element, of course).

  2. Embedded Style Sheet - a Style block in the HTML document
    You can place your style rules in a <style> element - ideally in the HTML header. This method is used when the rules will be applied just to the current document, rather than to a group of documents.

    <head>
    <style type="text/css">
    h3 {color:red;}            /* All h3's are red */
    h3.reallybig {font-size:250%;}  /* And some are very big */
    </style>
    </head>

  3. External Style Sheets - styles stored in a separate file.
    Style sheets can be placed in files, and then used in multiple documents. External style sheets are useful when you want to create a set of rules that will apply to several HTML documents. Like the style block, the style sheets are referenced in the HTML header. This is done using the link command. Style sheet documents should have a .css extention.

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

In style sheets, rules use braces to delimit the declaration, whereas inline styles use quotes.

V. Conditional Selectors

To give fine control of which elements a style should apply to, a style sheet may specify different types of conditions in selectors.

  1. Pseudo-classes (use ":") - Pseudo-classes represent the status of a hyperlink. They can be (link | visited | hover | active | focus).

    a:link {color:blue; text-decoration:underline;}
    a:visited {color:maroon;} /* visited inherits from link */

  2. ID Selectors (use "#") - The rule applies only to elements with the specified id.

    div#summary{color:forestgreen} /* Use this color only within the summary div */

  3. Descendant Selectors (use space) - The rule applies only to elements that occur within other elements.

    /* Use a light green background only on TH's in the summary div */
    div#summary th {background-color:lightgreen;}
    ol p {margin-left:0;} /* Don't add a margin to paragraphs inside any list */
    ul p {margin-left:0;}
    dl p {margin-left:0;}

  4. Child Selectors (use ">") - The rule applies only to elements that appear immediately subordinate to specified elements.

    body>p {margin-left:20px;} /* Define a margin only for top-level paragraphs. */
    ul>li {list-style-type:none} /* Always omit bullets from UL's; leave OL's alone */

  5. Adjacent Sibling Selectors (use "+") - The rule applies only to elements that appear immediately after (but not subordinate to) other specified elements.

    /* Don't add white space between an example and the next paragraph */
    p.example + p {margin-top:0}
    ul>li {list-style-type:none} /* Always omit bullets from UL's; leave OL's alone */

  6. Attribute Selectors - With expressions enclosed in square brackets, rules apply only when specific style sheet properties have certain values.  An asterisk may be specified to mean all tags.

    * [color:white;] {background-color:darkgrey;} /* Make sure white letters are visible */
    h1 [id] {color:blue} /* All h1's with ID values are in blue */
    a:link [target] {color:forestgreen;} /* Change link color if there is a target window */
    /* Highlight <span elements whose "hello" attribute has exactly the value "Cleveland" and whose "goodbye" attribute has exactly the value "Columbus" */
    span [hello="Cleveland"][goodbye="Columbus"] {background-color:aqua;font-weight:bold;}

VI. Inheritance

Many attributes defined in style sheets are inherited by the children of parent objects. For example, specifying font properties in the <body> element will change the default font for all elements within the document, and <div; elements are commonly used to set font and background color properties for elements within that div. Inheritance generally applies when it makes sense to inherit the property. Borders and widths and text wrapping, for example, are not inherited by the child objects, though widths can be drawn from parent objects by specifying width as a percentage, and many properties can be inherited by using the special value "inherit".

Some properties are not inherited where one might think they should be, however. As a result, rules such as the following one appear in many style sheets simply to supplement standard inheritance.

table, th, ul, ol, li {font-size:100%;}

VII. Specificity & Precedence

If multiple rules are applied to a single element, then these rules are all combined when displaying the object. For example, if the parent object has set the background color, and the rule for the current element set the font, then the current element will have both the background color from the parent, and the font specified in the current element.

For example:

<P style="background-color:aqua;">Aqua-colored text.
<strong style="font-size:150%;">This <em>strong</em> text is big and aqua, as well as bold.
</strong></P>

Looks like:

Aqua-colored text. This strong text is big and aqua, as well as bold.

It is common for one tag or class to be defined by more than one rule, particularly when some The same property can be set by more than one rule. But there is a precedence level for each rule that is used to determine which rule will be used. In general, the rule that most specifically targets the element that you are formatting will have precedence over other rules. The precidence rules are as follows (highest precedence will be used to display the object):

If there is more than one rule at the same level of precedence, then the more recently applied rule is used. In this two-rule example, paragraphs will be red because "red" was specified last:

p {color:green;}
p {color:red;}

VIII. Style Sheet Hints and Recommendations

  1. Relative URL's in stylesheets are generally computed as being relative to the stylesheet, not to the original page. However, some older browsers used the web page's URL as the base. So when practical, use root-relative URL's that work in both situations.

  2. When you specify a background image, always specify a background color, too, so that the font color is not washed out if the background image does not load.

  3. You can control whether your background image repeats using style sheets. This can be useful if the image was not meant to tile. Besides, setting the background not to scroll can be a desirable effect on your web page.

  4. When you specify a font, also specify a generic font, such as serif, sans-serif, or monospace. This will allow browsers to come up with reasonable alternatives when running on systems that don't happen to have a particular font.

    .bodytext{ font-family: times new roman, times, serif;}
    h3 {font-family:Arial, sans-serif;}
    .example {font-family: courier new, monospace;}

  5. Don't use absolute positioning. It often does not work and may result in a web page that is hard to read.

  6. Test your web page with at least two different web browers, (e.g. Microsoft Internet Explorer, and the Mozilla Foundation's Firefox.). And, if you are targeting the WWW at large, test with both PC's and Macintoshes (and possible, Unix workstations, as well.) What looks great in Internet Explorer will often not work at all in other browsers.

  7. If you can, Use a commercial style sheet editor that has some knowledge of attributes and values, and of browser compatibility with specific CSS properties.

IX. Common Style Attributes

Property and valueDescription
Text color and backgrounds
  color: [color reference]; Applies to virtually any block or inline element. See Color Chart
background-image: url( [url] ) Background attributes can be specified for most block-level elements. Typically used for <Body>, <table>, and <td>.
background-color: [color] See Color Chart
background-position: [position] [top left | top center | top right | center left | center center | center right | bottom left | bottom center | bottom right || x% y% || xpos ypos]
background-repeat: [repeat] [repeat | repeat-x | repeat-y | no-repeat ]
Lists
  list-style-type:[styletype] For <ul>: disk, circle, diamond, etc.
For <ol>: decimal, lower-roman, upper-roman, lower-alpha, upper-alpha, none.
list-style-image:url( [url] ) Use image in place of the shape for <ul>
Fonts
  font-family: [list of fonts] The list is comma-delimited, and should end with a generic font type: (serif | sans-serif | monospace || Cursive | Fantasy)
font-size: [length]; Non-zero values need units. Fixed length units are [ px | pt | in | cm]. Relative units are [em | ex | %]. Try to avoid fixed length units for fonts and for other values that should be affected when the user changes the font size.
font-weight:{value} [ bold | bolder | normal ]
line-height:{size} Expressed exactly like font sizes
text-decoration:{value} [ normal | underline || overline | line-through | blink ]
font-style:{value} [ normal | italic | oblique | inherit ]
Margins, padding, and borders - see the CSS Box Model
  margin: [top] [right] [bottom] [left];
margin-left: [left]; etc.
The margin is the area outside of the border. All 4 sides can be expressed in one rule, or separately. Each value is a length, typically in px, pt, or em.
padding: [top] [right] [bottom] [left];
padding-left: [left]; etc.
Padding is the area between content and border, on each side.
border: [top size] [top line] [top color] etc.
border-top: [top size] [top line] [top color]; etc.
border-size: [top] [right] [bottom] [left];
border-style: [top] [right] [bottom] [left];
border-color: [top] [right] [bottom] [left];
border-size-top: [size]; etc.
Borders have 3 characteristics for each side. All 12 values can be expressed in one rule, but borders are more commonly expressed with 1 value or 4 sides or three characteristics in one rule. The size is a length, rarely expressed in relative terms. Line type values are [ solid | dotted | dashed | none || double | groove | ridge | inset | outset ].
Text Wrapping
  text-align: [orientation]; [ right | center | left | justify ] Applies to text justification, not element positioning.
white-space: [wrap mode]; [ normal | nowrap || pre | pre-wrap | pre-line | inherit ]
Block positioning
  float: [orientation]; [ left | right | none | inherit ] Applies to the entire block-level elements, and is relative to adjacent block-level elements.
page-break-after: [when];
page-break-before: [when];
[always || avoid | auto | left | right]. There are widow and orphan attributes that are not widely supported.
@-Rules
  @media [mediatype]{[stylesheet]} The subordinate stylesheet (within brace) contains rules for specific media types. [ screen | print | handheld || tv | aural | braille | etc.]
@import "[url]"; Import styles from another style sheet. Must precede normal rules. Note the quotes.

X. Resources

  1. W3C Recommendations:
  2. W3C Style Sheet Properties Table
  3. w3schools HTML Tutorial
  4. w3schools CSS Tutorial