Web Development

How Cascading Style Sheets work

Cascading Style Sheets (CSS) are groups of style rules. Take a look at how they work.

By Matt Rotter, Charity Kahn, and Paul Anderson

Style sheets (also known as Cascading Style Sheets or CSS) are groups of style rules, which in turn are groups of properties that define how an HTML element appears in a Web browser--for instance, green, italic, and Arial. You can define styles either within an HTML document or in an external file attached to the HTML document. As an external file, a single style sheet can affect multiple pages--even a whole site. This makes page-wide or site-wide changes much easier to implement.

As the term Cascading Style Sheets implies, more than one style sheet can be used on the same document, with different levels of importance. If you define conflicting styles for the same HTML element, the innermost definition--the one closest to the individual tag--wins. For example, a tag's style attribute takes precedence over a surrounding element's style, which has priority over a style defined in the head of the document, which in turn wins over an attached style sheet. If conflicting styles are defined at the same level, the one occurring later wins.

So how do style sheets work? Say you want to create a page where each instance of <H3> text is green, italicized, and in the Arial typeface. Before the advent of CSS, you had to write the following HTML every time you used <H3>:

<EM><FONT face="Arial" color="green"><H3>This is a green, italic, Arial H3 header.</H3></FONT></EM>

But CSS lets you specify this style for all <H3> tags in a single step by defining what's called a selector:

H3 { font-family: Arial; font-style: italic; color: green }

The selector (in this case, the <H3> element) is followed by the style definition, which outlines the style for that selector. The rule font-family: Arial has the same effect as <FONT face="Arial">; font-style: italic has the same effect as <I>; and color: green has the same effect as <FONT color="green">. So once the style above is applied to the HTML document, every <H3> element will come out green, italic, and Arial while retaining its inherent HTML characteristics.

Matt Rotter and Charity Kahn are software engineers for CNET.com.

Paul Anderson is an associate technical editor for CNET Builder.com.