CSS in an HTML document

Learn about the ways you can combine styles with HTML.

By Matt Rotter, Charity Kahn, and Paul Anderson

There are four ways to combine styles with HTML. The two simplest ways are by defining styles in the head or the body of an HTML document. You can also create a separate style sheet and attach it to the HTML file in two different ways.

Defining Styles in the Head of the Document

The best way to define styles for a single HTML document is within the head of the document. (If you want to create a style sheet for use on several documents, link to an external style sheet instead.) Just place the selectors and their style definitions inside comment tags nested within a <STYLE> element, like so:

<STYLE type="text/css">
H3 { font-family: Arial; font-style: italic; color: green }
<H3>This is a green, italic, Arial H3 header.</H3>
<H3>So is this.</H3>

The type attribute of the <STYLE> element defines the type of style sheet being used—in this case, CSS. (At the moment, the only other possibility is "text/javascript" for Netscape's proprietary JavaScript style sheets. In the future, other style sheet languages may be added.)

The comment tags nested within the <STYLE> element ensure that the style rules won't appear or cause errors in older browsers. Any browser that doesn't support <STYLE> will simply ignore the element and the information inside.

Defining Styles In-Line

You can also define styles in the body of the document by adding the style attribute to an HTML tag. For instance, the following HTML code makes the first <H3> text (the one with the style attribute) green, italic, and Arial, but not the second:

<H3 style="font-family: Arial; font-style: italic; color: green">This is a green, italic, Arial H3 header.</H3>
<H3>This is an H3 header, but it's not green, italic, or Arial.</H3>

In most cases, this method defeats the purpose of using style sheets as global templates. It is useful, however, to create unique instances or exceptions. The <DIV> and <SPAN> elements are useful for applying a style to an arbitrary segment of the page.

While including styles in the HTML document is useful for small projects, it touches only the surface of style sheets' usefulness. Things really get interesting when you link to an external style sheet.

Matt Rotter and Charity Kahn are software engineers for

Paul Anderson is an associate technical editor for CNET

Editor's Picks