Cascading Style Sheets 101

 

T.I. McLaughlin

mcse, mct, b-admin, a+, webmaster

tom@mclaughlin.net

http://tom.mclaughlin.net

Table of Contents: This tutorial is used by permission from Marcus Kazmierczak.  His site can be found at http://blazonry.com and permission at http://blazonry.com/about.html

Cascading Style Sheets

Introduction

Cascading Style Sheets (CSS) are text files, or special text in a HTML file, which allows you to specify styles, attributes, and positioning of HTML objects.

 

What do you mean style?
Style is what gives an item its distinctive look or feel. For text it could be what font is used, what color, size, or spacing. It also applies to other HTML objects such as links, images, backgrounds, margins and borders.

 

How can I benefit by using CSS?
Some of the benefits to using CSS are more consistency, better layout and visual design, plus easier HTML coding. Also you can do things with style sheets that could never be done before.

  • consistency This would apply for larger sites, and many different developers, which is the environment I am currently working in for the Department of Education.

A site-global style sheet could be set up, which all pages would refer to. This sheet could include the look and feel you want for the complete site. Each page would maintain the same attributes throughout the site. The ability to change one item, on one page can change the same attribute on your whole site.

  • easier coding No more elaborate tables, and complicated HTML. This will also greatly benefits the large multi-contributor web environments.

The HTML code using style sheets is much simpler. The code reverts back to what it was in the early simple days. Just using header tags (H1, H2, ...), and paragraph tags with style sheets can produce a rich document, with the help of a SPAN and DIV tag here and there. (but that's getting ahead of myself)

  • rich design and layout Cascading Style Sheets bring professional layout and design control to HTML documents.

Here's a brief listing of what you can do with style sheets that you could only do with an elaborate work around, or not at all.

    • exact positioning of elements
    • font control (size, color, family)
    • white space control, margins, leading
    • background control (placement, repeat, ...)

 

One of the best features of style sheets is its ability to degrade nicely with older browsers. Most CSS styled documents still appear perfectly readable and formatted when viewed in a browser that does not support style sheets. It may not look as nice, but the content is still there.

 

Getting Started

You can view the source code of any of these HTML pages or example HTML pages by using your browsers "View Source" menu item. This is usually located in the "View" menu at the top, or by right-clicking the mouse.

 

Specifying the Style

The browser needs to know what style sheet or style elements being specified. There are several ways style can be specified:

 

1. Embedding a style Style sheet information can be placed in the HTML file itself. The following tags goes in the HEAD portion of the document:

<STYLE TYPE="text/css">
<!--
...style code goes here...
-->
</STYLE>


If you are familiar with JavaScript you will notice the same use of comments to fool older browser to ignore the extra code. The HTML specification states that browsers are to ignore tags they do not understand. Thus, an older browser reading this could would ignore the STYLE tag, and then bypass the style code because it is between HTML comments (<!--  -->)

 

2. Linking to a separate style sheet file. Instead of embedding the style code in each HTML file, you can put all of the style code in its own text file and link each document to that file. The following tag to link a style sheet is placed in the HEAD of the HTML document:

<LINK REL=STYLESHEET TYPE="text/css" HREF="style.css">

 

3. Importing a style sheet. You can also combine the above two items by importing a seperate style sheet into an individual HTML file. For example you can import a basic sheet, and then add on extra styles to it. The import command is placed in the STYLE section mentioned above and should be the first thing in that section:

<STYLE TYPE="text/css">
<!--
@import url(style.css);
... rest of style code goes here
-->
</STYLE>

 

4. Inline style Style can also be specified on a per HTML element basis. Below is an example of specifying a 1" margin on one specific paragraph.

<P STYLE="margin: 1.0in">This paragraph will have 1" margins all around.</P>

 

The Basics

The previous page explained how style sheets are referenced by the browser. This page expands on that and shows several working examples of style sheets.

Starting off with applying a color to a simple header tag, H1. Here is the complete code for the HTML file with a simple blue header.

<HTML><HEAD>
<STYLE TYPE="text/css">
<!--
H1 { color: blue }
-->
</STYLE>
</HEAD><BODY>
<H1> A blue header </H1>
</BODY></HTML>

The color tag used affects the Foreground color (text). If you wanted to have this style to be specified in a stand alone file, you would just save the code from the start STYLE tags to the close STYLE tag, inclusively. You would then reference the sheet using the LINK tag mentioned on the previous page.

 

If you want your header aligned in the center of the document, you can add the 'text-align' property as follows:

H1 { color: blue;
text-align: center; }

To save some space you can specify the attributes on the same line after the semi-colon.

H1 { color: blue; text-align: center; }

 

Classes

You do not need to define each and every tag specifically, but you can instead define classes and reference the class. Classes are defined by a name and a period in front of it. Here's an example:

<STYLE TYPE="text/css">
<!--
.myIndent { margin-left: 1.0in }
-->
</STYLE>

The HTML tags to reference the above .myIndent class is:

<H1 CLASS=myIndent>Indented Header</H1>
<P CLASS=myIndent>Also this whole paragraph would
be indented one inch</P>
<P>but this wouldn't be indented</P>

 

IDs

IDs are similar to classes except they work on a per element basis. ID use is actually discouraged by the W3C. The idea behind the ID is to define a certain style for a single specific element. They can not be used by multiple tags on the same page as the above example did.

IDs are referenced with a pound sign (#) and not a period as classes were.

#item1ID { font: 72pt Courier }

The HTML tag to reference this ID would be:

<SPAN ID=item1ID>some really large type</SPAN>

Being the tricky guy that I am, I have used a new tag, SPAN, to segue into the next topic.

 

SPAN and DIV

Two new tags have also been introduced to implement CSS. The tags alone do not have any predefined attributes, and are there for style to applied to them.

  • The SPAN tag is an inline element, which means it works with text or items that are on the same line, similar to the B, bold tag.
  • The DIV tag is a block element, which means it works with blocks of text or items, similar to the P, paragraph tag.

Ok, I think we have the basics out of the way. Let's move on and see what we can squeeze out of these style sheets.

Margins

Style sheets allow you to specify margins. What a nice addition to web pages. No longer will text be shoved right up against the sides of the browser, and no more extraneous tables to work around this. Well maybe not all table workarounds will disappear, but they can be much simpler.   With margins you can format the text within tables or any HTML element. Also you can indent single lines, whole paragraphs, image spacing, and more.   There are 5 margin properties, well really 4 and 1 shorthand. These properties are:

margin-top ,margin-bottom, margin-right, margin-left, margin (shorthand)

 

The values they accept are lengths, or percentages. The lengths are measured in pixels(px), inches(in), centimeters(cm), millimeters(mm), font point(pt), font height(em), and picas(pc).

The percentages are relative to the object, which could be the whole page, or 'inside' of another object, like a table. Negative values are accepted, but be careful when using them.

 

Examples

P { margin-top: 10px; margin-bottom: 75px;
margin-left: 50px; margin-right: 25px; }

This will define the above margins for everything in paragraph tags. Play with resizing your browser window, notice the margins stay the same width. The margin shorthand notation could have been used in the above and would have looked like this:

P { margin: 10px 25px 75px 50px }

The shorthand order being top - right - bottom - left.

Some even nicer short cuts, if using similar values, can be used. To set a 0.5in margin on each side you could use:

P { margin: 0.5in }

If you have the same top and bottom margins, and the same right and left margins you can use the following shorthand notation:

P { margin: 0.5in 1.0in }

This would create a half inch margin top and bottom, and a full inch margin on the left and right.

Here's an example to indent text

.indent1 { margin-left: 5%; margin-right: 30%; }
.indent2 { margin-left: 30%; margin-right: 5%; }

This example shows shifting paragraphs around using margins, this probably could be a quote or image in the now empty blank spots.

           

Fonts and Text

Finally some real control over fonts, yipee!!

There are 5 font properties, and 1 shorthand.

font-family, font-style, font-variant, font-weight, font-size, font (shorthand)

font-family

The font-family property specifies what font will be used, ie. Courier, Helvetica, Arial, etc... or if not available what general family to be used: serif, sans-serif, monospace.

The fonts are listed in preferred order. One nice thing about listing numerous fonts, is that a character which may not be available in one font will try to be extracted out of the next one listed.

 

 

Examples:

BODY { font-family: Times, TimesRoman, serif }
P { font-family: Helvetica, Verdana, Arial, sans-serif }
H1 { font-family:
Monaco, Courier, monospace }

Other generic font families that can be used are cursive and fantasy. The generic font families above are serif, sans-serif and monospace. If your font has more than one word use quotes.

.comix { font-family: "Comic Sans MS", sans-serif }

font-style

Valid values for font-style are normal, italic, and oblique. Very straight forward, oblique is similar to italic.

font-variant

Valid values for font-variant are normal and small-caps. Small caps displays the lowercase letters as scaled down uppercase letters.

font-weight

This property specifies what you want the font to weigh, ex. 50 lbs of pure Courier. Well not exactly, the weight of the font is the boldness, or lightness of the font. The valid values that you can assign font-weight are:

normal, bold, bolder, lighter and 100, 200, 300, 400, 500, 600, 700, 800, 900

Note: normal=400, bold=700

font-size

You guessed it, this specifies the size of the font. There are 5 different ways you can specify the font size. In no particular order, here they are:

absolute size:
point size: ie. 7pt, 22pt, 14pt, 36pt, 72pt, ...
pixel size: ie. 100px, 45px, 90px, 10px, ...
relative size:
key words: xx-small, x-small, small,
medium, large, x-large, xx-large
percentage: 24%, 58%, 150%, 10%, 100%, ...
ems: .24em, .58em, 1.5em, .1em, 1.0em, ...

For font-size, ems are equivalent to percentages. Also you only put in the values for the size you want, do not specify the descriptive words absolute size, point size, etc...

Pixel sizing is not recommended by Netscape. The relative sizes are relative to the parent element. For example, if a base font size is set in the BODY, then the the relative sizing is relative to that base font size.

font

Font is a shorthand notation to keep our sheets a little cleaner and neater. The order of the shorthand is 'font-style' 'font-variant' 'font-weight' 'font-size' 'font-family' Also keeping with normal typographical syntax, you can specify the leading, or line-height along with the font-size by using font-size/line-height.

Examples:

H1 { font: bolder 72pt Impact, "New SchoolBook", sans-serif }
H2 { font: 700 36pt/48pt
Monaco, Courier, monospace }
H5 { font: lighter 12pt Times, TimesRoman, serif }

Text

There are 5 text properties that you can specify.

word-spacing, letter-spacing, text-decoration, vertical-align, text-transform, text-align, text-indent, line-height

letter-spacing and word-spacing

Exactly how it sounds this specify the spacing between letters and words. The valid values are length values, such as em, px, pt, %,...

Examples:

P { word-spacing: 0.75em; letter-spacing: 10px; }

text-decoration

The text-decoration values you can assign to it are: normal, underline, overline, line-through, and blink (blech!!) Each one is fairly self-explanatory.

vertical-align

Valid values are: baseline, sub, super, top, text-top, middle, bottom, text-bottom.

I am not exactly sure the minute differences between all of these, play around with different alignments and see what does what.

text-transform

I think this property is one of the neater properties that I probably will never use. The property can transform the text to all uppercase, all lowercase, and capitalized. The valid values are: none, capitalize, uppercase, lowercase.

I'll probably never use them, because I would just type the text how I want it, and wouldn't need a style sheet to control it, but it may be useful somehow.

text-align

This probably should have been called horizontal-align, since they have a vertical align, but my guess is that that is to hard to spell and type in numerous times. Valid values for text-align are: left, right, center, and justify.

text-indent

Indented a paragraph, what a concept. Valid values are length and percentages. This property will indent the first line in a paragraph, the sepecified length or percentage.

Examples:

.indent1 { text-indent: 1.0em; }
.indent2 { text-indent: 30px; }

line-height

This allows you specify the height of a line, which will allow you to specify the distance between two lines. I found this a little tricker to use, it doesn't work well as an inline property, I found as a paragraph property works pretty good.
Valid values are: length and percentages, negative values are not allowed.

Example:

P.listi { line-height: 80%; }

This property is used on this page twice, when I list out the valid properties that Font and Text have.

           

Backgrounds

There are 5 background properties, and 1 shorthand.

background-color, background-image, background-repeat, background-attachment, background-position, background (shorthand)

The nice thing about backgrounds is that it doesn't have to apply to the whole screen, as the normal background HTML tag does. To apply a background to the whole page, you use it in the body tag.

You can specify backgrounds in paragraphs, table cells, headers and almost anything else you want.

 

 

background-color and background-image

These two are very straight forward. For background-color the valid values are colors, be it rgb, hex, or color name, and transparent, which makes the background transparent.

There are only two values for background-image, none and a url to point to an image object.

Examples:

P.bg1 { background-color: #000000;
color: #FFFFFF; /* color the text white */ }
P.bg2 { background-image: url(images/bg1.gif) }

background-repeat

Valid values are: repeat, repeat-x, repeat-y, and no-repeat. A value of repeat, repeats the background horizontally and vertically. repeat-x only repeats the background in the horizontal direction, repeat-y vertical direction. And as you might have thought no-repeat does not repeat the background at all.

background-attachment

There are two values for background-attachment, scroll and fixed. A valid you of scroll is what is common with browsers today. The background scrolls along as you do. A value of fixed will keep the background fixed, with the text and other goodies scrolling on top of it.

background-position

You can specify where the background is to be placed with this property. Valid values are: length, percentage, top, center, bottom, left, right.

For example you have a table cell which is bigger than the background image, and you want it to be in the bottom right corner of that cell. Here's the code:

TD.bg1 { background-position: bottom right } or TD.bg1 { background-position: 100% 100% }

Both of these will do the same thing, you can also position the backgrounds by specifying the pixels offset of the image.

background (shorthand)

The shorthand notation for background follows the order: background-color, background-image, background-repeat, background-attachment, and background-position

Example:

P { background: white url(bg1.gif) no-repeat fixed }

 

Miscelleanous Topics

Two topics that should be covered that didn't fall into another category, hence the all inclusive miscelleanous.

Inheritance

A nice thing about style sheets is that types can inherit certain properties by their parent object. Sound confusing, its not. One of the common inheritance features in standard HTML is the UL and LI tag (on some browsers).

When a LI tag is used inside of an UL tag, the list bullet is smaller. The LI tag changes due to its surrondings, specifically inside a UL tag.

To do this in CSS is rather easy. In this example I'll make the LI text smaller when it is inside a UL tag.

example:
   UL LI { text-size: 80% }

That's all there's to it. Now every LI tag used will be 80% smaller when it is inside a UL tag.


Float and Clear

Two properties that go together like chocolate and peanut-butter are float and clear. Float allows an object to float in its space relative to the other objects around it. I used this on the introduction page in the benefits section. You can use float to produce drop caps and other nice effects. Clear is used to stop a float.   The valid values for float are none, left, and right. The valid values for clear are none, left, right and both.

Example:
   .first { font-size: 26pt; float: left; }
   .nomore { clear: left; }

I have used the .nomore class at different points in different paragraphs, to show how to stop the floating object. The last paragraph I did not use a clear.

....more to come as I learn it....

Apply your style to style sheets. Experiment and see what you can do with this new tool.

There are numerous properties I did not mention, most are as straight forward as the rest of the properties. Some of these are padding, display, white-space, list style (you can make your LI's images), and borders. For a complete listing of properties see the quick reference guide or the W3C's recommendation paper.

 

Tricks and Tips

Think about Non-CSS browsers

One very nice thing about style sheets, if used properly non-css compliant browsers will still display formatted content, somewhat. Of course it will not be as nice and fancy as a CSS browser, but something will still show, and no error messages. By far the most annoying aspect of JavaScripts. You can't sneak an error by there.

You can let the non-css browsers know that you are using style sheets. A good way of doing this is using the display: none command. I have done that on some of my pages, if it shows up than you are not fully css-compliant.

Example:

.inviso { display: none; }
<P CLASS=inviso> this page uses style sheets, you are missing out.</P>

Also when you are formatting your page try to format in such a way that non-CSS browsers will still maintain some formatting, such as using headers. Using appropriate headers in their appropriate spots will still enlarge, and bold font when appropriate. The non-CSS browser will not show the font or color or alignment you assigned but it will still show some formatting.

Only using SPAN and DIV will not show any special formatting to non-CSS browsers.

 

Fancy Text

You can create fancy titles and text effects using just style sheets. Here an example of a title with a box around the first letter. A nice effect without requiring an image.

Example:

<STYLE TYPE="text/css">
.intro1 { color: blue; background: #333399; font-size: 36pt; }
.intro2 { color: #333399; font-size: 26pt; }
</STYLE>
<H1><SPAN CLASS=intro1>I</SPAN>
<SPAN CLASS=intro2>ntroduction</SPAN></H1>

H1 tags were used around to so non-CSS browsers will still see a header type tag, just not the coloring or box.

 

Boxes with Border Lines

The left hand navigation boxes I have on blazonry.com use style sheets instead of complicated tables to draw the one pixel box. An example is the navigation on the top left of this page. The style sheet code to do this is:

<STYLE TYPE="text/css">
.box175 {
   width: 175px;
   border: 1px solid #000099;
   padding: 4px;
}
</STYLE>

<DIV CLASS="box175">
Content
more content
etc...
</DIV>

 

Problems

CSS has not been implemented completely and properly in the two major browsers. Lip-service is being given to support the complete W3C recommendation, which came out way bac in Dec. 1996, but not all CSS features are implemented. Opera, an alternative browser, has the best standards compliance for CSS and HTML.

This should not scare you away from using Style Sheets, most of the common properties such as fonts, text, and margins are all implemented. Just be sure to test how everything looks on various browsers, as you always should be doing anyways.

Linking Style Sheets to HTML

There are many ways to link style sheets to HTML, each carrying its own advantages and disadvantages. New HTML elements and attributes have been introduced to allow easy incorporation of style sheets into HTML documents.

An external style sheet may be linked to an HTML document through HTML's LINK element:

<LINK REL=StyleSheet HREF="style.css" TYPE="text/css">
<LINK REL=StyleSheet HREF="color-8b.css" TYPE="text/css" TITLE="8-bit Color Style" MEDIA="screen, print">
<LINK REL="Alternate StyleSheet" HREF="color-24b.css" TYPE="text/css" TITLE="24-bit Color Style" MEDIA="screen, print">
<LINK REL=StyleSheet HREF="aural.css" TYPE="text/css" MEDIA=aural>

The <LINK> tag is placed in the document HEAD. The optional TYPE attribute is used to specify a media type--text/css for a Cascading Style Sheet--allowing browsers to ignore style sheet types that they do not support. Configuring the server to send text/css as the Content-type for CSS files is also a good idea.

External style sheets should not contain any HTML tags like <HEAD> or <STYLE>. The style sheet should consist merely of style rules or statements. A file consisting solely of P { margin: 2em } could be used as an external style sheet.

The <LINK> tag also takes an optional MEDIA attribute, which specifies the medium or media to which the style sheet should be applied. Possible values are

·                     screen (the default value), for presentation on non-paged computer screens;

·                     print, for output to a printer;

·                     projection, for projected presentations;

·                     aural, for speech synthesizers;

·                     braille, for presentation on braille tactile feedback devices;

·                     tty, for character cell displays (using a fixed-pitch font);

·                     tv, for televisions;

·                     all, for all output devices.

Multiple media are specified through a comma-separated list or the value all.

Netscape Navigator 4.x incorrectly ignores any linked or embedded style sheets declared with MEDIA values other than screen. For example, MEDIA="screen, projection" will cause the style sheet to be ignored by Navigator 4.x, even if the presentation device is a computer screen. Navigator 4.x also ignores style sheets declared with MEDIA=all.

The REL attribute is used to define the relationship between the linked file and the HTML document. REL=StyleSheet specifies a persistent or preferred style while REL="Alternate StyleSheet" defines an alternate style. A persistent style is one that is always applied when style sheets are enabled. The absence of the TITLE attribute, as in the first <LINK> tag in the example, defines a persistent style.

A preferred style is one that is automatically applied, such as in the second <LINK> tag in the example. The combination of REL=StyleSheet and a TITLE attribute specifies a preferred style. Authors cannot specify more than one preferred style.

An alternate style is indicated by REL="Alternate StyleSheet". The third <LINK> tag in the example defines an alternate style, which the user could choose to replace the preferred style sheet.

Note that current browsers generally lack the ability to choose alternate styles.

A single style may also be given through multiple style sheets:

<LINK REL=StyleSheet HREF="basics.css" TITLE="Contemporary">
<LINK REL=StyleSheet HREF="tables.css" TITLE="Contemporary">
<LINK REL=StyleSheet HREF="forms.css" TITLE="Contemporary">

In this example, three style sheets are combined into one "Contemporary" style that is applied as a preferred style sheet. To combine multiple style sheets into a single style, one must use the same TITLE with each style sheet.

An external style sheet is ideal when the style is applied to numerous pages. With an external style sheet, an author could change the look of an entire site by simply changing one file. As well, most browsers will cache an external style sheet, thus avoiding a delay in page presentation once the style sheet is cached.

Microsoft Internet Explorer 3 for Windows 95/NT4 does not support BODY background images or colors from linked style sheets. Given this bug, authors may wish to provide another mechanism for including a background image or color, such as embedding or inlining the style, or by using the BACKGROUND attribute of the BODY element.

Embedding a Style Sheet

A style sheet may be embedded in a document with the STYLE element:

<STYLE TYPE="text/css" MEDIA=screen>
<!--
  BODY  { background: url(foo.gif) red; color: black }
  P EM  { background: yellow; color: black }
  .note { margin-left: 5em; margin-right: 5em }
-->
</STYLE>

The STYLE element is placed in the document HEAD. The required TYPE attribute is used to specify a media type, as is its function with the LINK element. Similarly, the TITLE and MEDIA attributes may also be specified with STYLE.

Older browsers, unaware of the STYLE element, would normally show its contents as if they were part of the BODY, thus making the style sheet visible to the user. To prevent this, the contents of the STYLE element should be contained within an SGML comment (<!-- comment -->), as in the preceding example.

An embedded style sheet should be used when a single document has a unique style. If the same style sheet is used in multiple documents, then an external style sheet would be more appropriate.

Importing a Style Sheet

A style sheet may be imported with CSS's @import statement. This statement may be used in a CSS file or inside the STYLE element:

<STYLE TYPE="text/css" MEDIA="screen, projection">
<!--
  @import url(http://www.htmlhelp.com/style.css);
  @import url(/stylesheets/punk.css);
  DT { background: yellow; color: black }
-->
</STYLE>

Note that other CSS rules may still be included in the STYLE element, but that all @import statements must occur at the start of the style sheet. Any rules specified in the style sheet itself override conflicting rules in the imported style sheets. For example, even if one of the imported style sheets contained DT {background: aqua}, definition terms would still have a yellow background.

The order in which the style sheets are imported is important in determining how they cascade. In the above example, if the style.css imported style sheet specified that STRONG elements be shown in red and the punk.css style sheet specified that STRONG elements be shown in yellow, then the latter rule would win out, and STRONG elements would be in yellow.

Imported style sheets are useful for purposes of modularity. For example, a site may separate different style sheets by the selectors used. There may be a simple.css style sheet that gives rules for common elements such as BODY, P, H1, and H2. In addition, there may be an extra.css style sheet that gives rules for less common elements such as CODE, BLOCKQUOTE, and DFN. A tables.css style sheet may be used to define rules for table elements. These three style sheets could be included in HTML documents, as needed, with the @import statement. The three style sheets could also be combined via the LINK element.

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>

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, an author 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.

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:

<H1 CLASS=punk>Proprietary Extensions</H1>
<P CLASS=warning>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 author decided to change the style of the class to a different color, or if the author 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:

<P ID=wdg97>Welcome to the Web Design Group!</P>

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 authors 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:

<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>
<P>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.</P>
<P>Since DIV may contain other block-level containers, it is useful for marking large sections of a document, such as this note.</P>
<P>The closing tag is required.</P>
</DIV>

A Note about Validation

Few CSS-styled documents will validate at the HTML 3.2 (Wilbur) level. HTML 3.2 does not define the SPAN element, nor the CLASS, STYLE, or ID attributes, and 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 safely ignored. Documents using these elements and attributes may be validated against HTML 4.0.


Resources

 

W3C Style Sheets
A general information site by the W3 Consortium on style sheets. Includes links to software, reference material, and explanation of what style sheets are.