Uncle Jim's CSS-P Tutorials: Introduction to Cascading Style Sheets

Article one of a series by Jim Stiles.

So, What is a Style Sheet?

Simply stated, a style sheet is made up of style rules that tell a browser how to present a document. There are various ways of linking these style rules to your HTML documents, but the simplest method for starting out is to use HTML's STYLE element. This element is placed in the document HEAD, and it contains the style rules for the page.

Note that while the STYLE element is a good method of experimenting with style sheets, it has disadvantages that should be considered before one uses this method in practice. The advantages and disadvantages of the various methods are discussed in the section on linking style sheets to HTML.

CSS Levels

CSS has various levels and profiles. Roughly speaking, desktop browsers implement level 1, 2 or 3, other programs implement the appropriate profile for their platform: cell phone, PDA, television, printer, speech synthesizer, etc.

CSS level 3 is currently under development. It includes all of level 2 and extends it with new selectors, fancy borders and backgrounds, vertical text, user interaction, speech and much more.
CSS level 2 revision 1 (“CSS 2.1”) contains all of CSS level 1 and adds absolutely positioned elements, automatic numbering, page breaks, right to left text and other things.
CSS level 1 , an earlier version from 1996 to 1999, contains properties for fonts, margins, colors, etc., that nearly all profiles of CSS need.
CSS Mobile Profile 1.0 is for devices such as mobile phones and PDAs.
CSS TV Profile 1.0 is for browsers that run on television sets (WebTV).
CSS Print Profile is still a draft. It is aimed at low-cost printers.


Each rule is made up of a selector; usually an HTML element such as BODY, P, or EM; and the style to be applied to the selector. There are numerous properties that may be defined for an element. Each property takes a value, which together with the property describes how the selector should be presented.

Style rules are formed as follows:

selector { property: value }
Multiple style declarations for a single selector may be separated by a semicolon:
selector { property1: value1; property2: value2 }
As an example, the following code segment defines the color and font-size properties for H1 and H2 elements:
<STYLE TYPE="text/css">
  H1 { font-size: x-large; color: red }
  H2 { font-size: large; color: blue }
</STYLE>

The above style sheet tells the browser to show level-one headings in an extra-large, red font, and to show level-two headings in a large, blue font. The CSS1 Specification formally defines all properties and values available. The properties and values are also given in the CSS Properties section of this site.

CSS Structure and Rules

- An introduction to the various kinds of selectors, pseudo-classes, pseudo-elements, and cascading order.

Basic Syntax
Rules
Selectors

Any HTML element is a possible CSS1 selector. The selector is simply the element that is linked to a particular style. For example, the selector in the below example is P
P { text-indent: 3em }

Class Selectors

A simple selector can have different classes, thus allowing the same element to have different styles. For example, a web developer may wish to display code in a different color depending on its language:
code.html { color: #191970 }
code.css  { color: #4b0082 }
The above example has created two classes, css and html for use with HTML's CODE element. The CLASS attribute is used in HTML to indicate the class of an element, e.g.,

Only one class is allowed per selector. For example, code.html.proprietary is invalid.


Classes may also be declared without an associated element:

.note { font-size: small }
In this case, the note class may be used with any element.

A good practice is to name classes according to their function rather than their appearance. The note class in the above example could have been named small, but this name would become meaningless if the web developer decided to change the style of the class so that it no longer had a small font size.

ID Selectors

ID selectors are individually assigned for the purpose of defining on a per-element basis. This selector type should only be used sparingly due to its inherent limitations. An ID selector is assigned by using the indicator "#" to precede a name. For example, an ID selector could be assigned as such:
#svp94O { text-indent: 3em }
This would be referenced in HTML by the ID attribute:
<P ID=svp94O>Text indented 3em</P>
and would look like the following:

Text indented 3em



Contextual Selectors

Contextual selectors are merely strings of two or more simple selectors separated by white space. These selectors can be assigned normal properties and, due to the rules of cascading order, they will take precedence over simple selectors. For example, the contextual selector in the following example:
P EM { background: yellow }
is P EM. This rule says that emphasized text within a paragraph should have a yellow background; emphasized text in a heading would be unaffected.

Declarations

Properties: A property is assigned to a selector in order to manipulate its style. Examples of properties include color, margin, and font.

Values: The declaration value is an assignment that a property receives. For example, the property color could receive the value red.

Grouping

In order to decrease repetitious statements within style sheets, grouping of selectors and declarations is allowed. For example, all of the headings in a document could be given identical declarations through a grouping:
H1, H2, H3, H4, H5, H6 {
  color: red;
  font-family: sans-serif }

Inheritance

Virtually all selectors which are nested within selectors will inherit the property values assigned to the outer selector unless otherwise modified. For example, a color defined for the BODY will also be applied to text in a paragraph.

There are some cases where the inner selector does not inherit the surrounding selector's values, but these should stand out logically. For example, the margin-top property is not inherited; intuitively, a paragraph would not have the same top margin as the document body.

Comments
Comments are denoted within style sheets with the same conventions that are used in C programming. A sample CSS1 comment would be in the format:
/* COMMENTS CANNOT BE NESTED */

Pseudo-classes and Pseudo-elements

Pseudo-classes and pseudo-elements are special "classes" and "elements" that are automatically recognized by CSS-supporting browsers. Pseudo-classes distinguish among different element types (e.g., visited links and active links represent two types of anchors). Pseudo-elements refer to sub-parts of elements, such as the first letter of a paragraph.

Rules with pseudo-classes or pseudo-elements take the following form:
selector:pseudo-class { property: value }
or
selector:pseudo-element { property: value }

Pseudo-classes and pseudo-elements should not be specified with HTML's CLASS attribute. Normal classes may be used with pseudo-classes and pseudo-elements as follows:
selector.class:pseudo-class { property: value }
or
selector.class:pseudo-element { property: value }

Anchor Pseudo-classes

Pseudo-classes can be assigned to the A element to display links, visited links and active links differently. The anchor element can give the pseudo-classes link, visited, or active. A visited link could be defined to render in a different color and even a different font size and style.

An interesting effect could be to have a currently selected (or "active") link display in a slightly larger font size with a different color. Then, when the page is re-selected the visited link could display in a smaller font size with a different color. The sample style sheet might look like this:
A:link    { color: red }
A:active  { color: blue; font-size: 125% }
A:visited { color: green; font-size: 85% }

First Line Pseudo-element

Often in newspaper articles, such as those in the Wall Street Journal, the first line of text in an article is displayed in bold lettering and all capitals. CSS1 has included this capability as a pseudo-element. A first-line pseudo-element may be used in any block-level element (such as P, H1, etc.). An example of a first-line pseudo-element would be:
P:first-line {
  font-variant: small-caps;
  font-weight: bold }

First Letter Pseudo-element

The first-letter pseudo-element is used to create drop caps and other effects. The first letter of text within an assigned selector will be rendered according to the value assigned. A first-letter pseudo-element may be used in any block-level element. For example:
P:first-letter { font-size: 300%; float: left }
would create a drop cap three times the normal font size.

Cascading Order

When multiple style sheets are used, the style sheets may fight over control of a particular selector. In these situations, there must be rules as to which style sheet's rule will win out. The following characteristics will determine the outcome of contradictory style sheets.

! important

Rules can be designated as important by specifying ! important. A style that is designated as important will win out over contradictory styles of otherwise equal weight. Likewise, since both developer and reader may specify important rules, the developer's rule will override the reader's in cases of importance. A sample use of the ! important statement:
BODY { background: url(bar.gif) white;
       background-repeat: repeat-x ! important }

Origin of Rules

As was previously mentioned, both developers and readers have the ability to specify style sheets. When rules between the two conflict, the web developer's rules will win out over reader's rules of otherwise equal weight. Both developer's and reader's style sheets override the browser's built-in style sheets.

Web developers should be wary of using ! important rules since they will override any of the user's ! important rules. A user may, for example, require large font sizes or special colors due to vision problems, and such a user would likely declare certain style rules to be ! important, since some styles are vital for the user to be able to read a page. Any ! important rules will override normal rules, so developers are advised to use normal rules almost exclusively to ensure that users with special style needs are able to read the page.

Selector Rules: Calculating Specificity

Style sheets can also override conflicting style sheets based on their level of specificity, where a more specific style will always win out over a less specific one. It is simply a counting game to calculate the specificity of a selector.

Count the number of ID attributes in the selector.
Count the number of CLASS attributes in the selector.
Count the number of HTML tag names in the selector.

Finally, write the three numbers in exact order with no spaces or commas to obtain a three digit number. (Note, you may need to convert the numbers to a larger base to end up with three digits.) The final list of numbers corresponding to selectors will easily determine specificity with the higher numbers winning out over lower numbers. Following is a list of selectors sorted by specificity:
#id1         {xxx} /* a=1 b=0 c=0 --> specificity = 100 */
UL UL LI.red {xxx} /* a=0 b=1 c=3 --> specificity = 013 */
LI.red       {xxx} /* a=0 b=1 c=1 --> specificity = 011 */
LI           {xxx} /* a=0 b=0 c=1 --> specificity = 001 */


Order of Specification

To make it easy, when two rules have the same weight, the last rule specified wins.

Inlining Style

Style may be inlined using the STYLE attribute. The STYLE attribute may be applied to any BODY element (including BODY itself) except for BASEFONT, PARAM, and SCRIPT. The attribute takes as its value any number of CSS declarations, where each declaration is separated by a semicolon. An example follows:
<P STYLE="color: red; font-family: 'New Century Schoolbook', serif"> This paragraph is styled in red with the New Century Schoolbook font, if available.</P>

This paragraph is styled in red with the New Century Schoolbook font, if available.

Note that New Century Schoolbook is contained within single quotes in the STYLE attribute since double quotes are used to contain the style declarations. Inlining style is far more inflexible than the other methods. To use inline style, one must declare a single style sheet language for the entire document using the Content-Style-Type HTTP header extension. With inlined CSS, a developer must send text/css as the Content-Style-Type HTTP header or include the following tag in the HEAD:
<META HTTP-EQUIV="Content-Style-Type" CONTENT="text/css">
Inlining style loses many of the advantages of style sheets by mixing content with presentation. As well, inlined styles implicitly apply to all media, since there is no mechanism for specifying the intended medium for an inlined style. This method should be used sparingly, such as when a style is to be applied on all media to a single occurrence of an element. If the style should be applied to a single element instance but only with certain media, use the ID attribute instead of the STYLE attribute.

Style Attributes


The CLASS Attribute

The CLASS attribute is used to specify the style class to which the element belongs. For example, the style sheet may have created the punk and warning classes:
.punk     { color: lime; background: #ff80c0 }
P.warning { font-weight: bolder; color: red; background: white }
These classes could be referenced in HTML with the CLASS attribute:

Proprietary Extensions

Many proprietary extensions can have negative side-effects, both on supporting and non-supporting browsers

In this example, the punk class may be applied to any BODY element since it does not have an HTML element associated with it in the style sheet. Using the example's style sheet, the warning class may only be applied to the P element. A good practice is to name classes according to their function rather than their appearance. The warning class in the previous example could have been named red, but this name would become meaningless if the developer decided to change the style of the class to a different color, or if the developer wished to define an aural style for those using speech synthesizers.

Classes can be a very effective method of applying different styles to structurally identical sections of an HTML document. For example, this page uses classes to give a different style to CSS code and HTML code.

The ID Attribute

The ID attribute is used to define a unique style for an element. A CSS rule such as:
#wdg97 { font-size: larger }
may be applied in HTML through the ID attribute:

Welcome to Uncle Jim's Web Designs !

Each ID attribute must have a unique value over the document. The value must be an initial letter followed by letters, digits, or hyphens. The letters are restricted to A-Z and a-z.

Note that HTML 4.0 allows periods in ID attribute values, but CSS1 does not allow periods in ID selectors. Also note that CSS1 allows the Unicode characters 161-255 as well as escaped Unicode characters as a numeric code, but HTML 4.0 does not allow these characters in an ID attribute value. The use of ID is appropriate when a style only needs to be applied once in any document. ID contrasts with the STYLE attribute in that the former allows medium-specific styles and can also be applied to multiple documents (though only once in each document).

The SPAN Element

The SPAN element was introduced into HTML to allow developers to give style that could not be attached to a structural HTML element. SPAN may be used as a selector in a style sheet, and it also accepts the STYLE, CLASS, and ID attributes. SPAN is an inline element, so it may be used just as elements such as EM and STRONG in HTML. The important distinction is that while EM and STRONG carry structural meaning, SPAN has no such meaning. It exists purely to apply style, and so has no effect when the style sheet is disabled.

Some examples of SPAN follow:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD>
<TITLE>Example of SPAN</TITLE>
<META HTTP-EQUIV="Content-Style-Type" CONTENT="text/css">
<STYLE TYPE="text/css" MEDIA="screen, print, projection">

  .firstwords { font-variant: small-caps }

</STYLE>
</HEAD>
<BODY>
 -->
<P><SPAN CLASS=firstwords>The first few words</SPAN> of a
paragraph could be in small-caps. Style may also be inlined, such as
to change the style of a word like <SPAN STYLE="font-family: Arial">
Arial</SPAN>.</P>

The DIV Element

The DIV element is similar to the SPAN element in function, with the main difference being that DIV (short for "division") is a block-level element. DIV may contain paragraphs, headings, tables, and even other divisions. This makes DIV ideal for marking different classes of containers, such as a chapter, abstract, or note. For example:
<DIV CLASS=note>
<H1>Divisions</H1>
</DIV>

The DIV element is defined in HTML 3.2, but only the ALIGN attribute is permitted in HTML 3.2. HTML 4.0 adds the CLASS, STYLE, and ID attributes, among others. Since DIV may contain other block-level containers, it is useful for marking large sections of a document, such as this note. The closing tag is required.

Validation

Few CSS-styled documents will validate at the HTML 3.2 level due to non-support of the SPAN element, or the CLASS, STYLE, or ID attributes. HTML 3.2 also lacks support for the TYPE and MEDIA attributes on the LINK and STYLE elements. These style-related elements and attributes are not harmful to non-supporting browsers, as they are simply ignored. Documents using these elements and attributes may be validated against HTML 4.0.

Before you validate

Here are some common mistakes, warning and tips to remember when constructing your style sheets:

CSS Validating Tools

Listed below are the most popular on-line validation tools:


Next, we will go over the descriptions of the various properties available in Cascading Style Sheets

<<< Introduction | Home | Next >>>