Visit Mozilla.org

CSS:Getting Started:Why use CSS

From MDC


This page explains why documents use CSS. You use CSS to add a stylesheet to your sample document.

[edit] Information: Why use CSS?

CSS helps you to keep the information content of a document separate from the details of how to display it. The details of how to display the document are known as its style. You keep the style separate from the content so that you can:

  • Avoid duplication
  • Make maintenance easier
  • Use content with different styles for different purposes
Example
Your web site might have thousands of pages that look similar. Using CSS, you store the style information in common files that all the pages share.

When a user displays a web page, the user's browser loads the style information along with the content of the page.

When a user prints a web page, you provide different style information that makes the printed page easy to read.

In general with CSS, you use the markup language to describe the information content of the document, not its style. You use CSS to specify its style, not its content. (Later in this tutorial, you will see some exceptions to this arrangement.)

More details
A markup language like HTML also provides some ways to specify style.

For example, in HTML you can use a <b> tag to make text bold, and you can specify the background color of a page in it's <body> tag.

When you use CSS, you normally avoid using these features of the markup language so that all your document's style information is in one place.

[edit] Action: Creating a stylesheet

Create another text file in the same directory as before. This file will be your stylesheet. Name it: style1.css

In your CSS file, copy and paste this one line, then save the file:

strong {color: red;}

[edit] Linking your document to your stylesheet

To link your document to your stylesheet, edit your HTML file. Add the line shown here in bold:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; 
charset=iso-8859-1">
  <title>Sample document</title>
  <link rel="stylesheet" type="text/css" href="style1.css">
  </head>
  <body>
    <p>
      <strong>C</strong>ascading
      <strong>S</strong>tyle
      <strong>S</strong>heets
    </p>
  </body>
</html>

Save the file and refresh your browser's display. The stylesheet makes the initial letters red, like this:

Cascading Style Sheets
Challenge
In addition to red, CSS allows some other color names.

Without looking up a reference, find five more color names that work in your stylesheet.

[edit] What next?

If you had difficulty understanding this page, or if you have other comments about it, please contribute to its Discussion page.

Now you have a sample document linked to a separate stylesheet, you are ready to learn more about how your browser combines them when it displays the document: How CSS works