Updated 7/7/2010 at 8:15 p.m.

Cascading Stylesheets


Introduction

The currently accepted, most useful way of structuring and formatting HTML pages is a technology called "Cascading Style Sheets", or CSS for short. The W3C (World Wide Web Consortium) first proposed CSS back in 1996, and CSS is now working in all of the major browsers.

You can very precisely determine how you want your Web pages to look, with CSS rules. You can control the appearance of text (fonts), position elements (images and such) on the page, control backgrounds, and do all sorts of formatting tricks that you can't do with HTML alone.

There are three types, or flavors, of stylesheets. The three types of stylesheets are inline, embedded, and external stylesheets.

Stylesheets contain style rules. We will talk about a bunch of different rules as we go through this class.

Now we come to the reasons why stylesheets are called "cascading" stylesheets.

This adding and overriding of rules is one reason that we use the term "cascading" in describing stylesheets. Additionally,

And this inheritance of rules by nested tags is another reason that we describe stylesheets as "cascading".


Stylesheet Syntax

The basic syntax of CSS rules in external and embedded stylesheets is:

  selector {property:value; property:value}
The basic syntax of CSS rules in inline stylesheets is:
  style="property:value; property:value"

You should note these points about the syntax:


The selector in external and embedded stylesheets tells the browser what you want to apply the rules/declarations to. A selector can be one of three kinds:

  1. an element selector
    • As a reminder, HTML elements are tags such as the body, paragraph (p), div, and span tags.
    • An element selector name is simply the name of the HTML tag that it will apply its rules to. For instance, if you want to apply some rules to HTML paragraphs, your selector would look like this in the stylesheet:
      p
      {
      }
    • An element selector is used by the browser for every such element in your page, unless you do something else to override these rules (more on that later).
    • An element selector's rules are applied automatically by the browser, simply by your having that HTML element in your page. For instance, if you have a p selector in your (external or embedded) stylesheet, the rule(s) associated with the p selector will be applied to your paragraphs without your doing anything (else) to the paragraph tags in your page (but see below for how you apply an external stylesheet to your pages).

  2. a class selector
    • A class selector name (in the stylesheet itself) starts with a period, like this:
      .normalText
      {
      }
    • You can name your class selectors almost anything, but your class names must not have spaces in them.
    • A class selector's rules may be used multiple times in a page.
    • In the HTML page, a class selector is applied to an HTML tag as a class attribute.
    • Here is an example of a class attribute (applied here to a paragraph tag):
      <p class="normalText">
  3. an id selector
    • An id selector name (in the stylesheet itself) starts with a pound sign, like this:
      #mainParagraph
      {
      }
    • You can name your id selectors almost anything, but your id names must not have spaces in them.
    • An id selector may be used only once in a page. It may be used in other pages, but only once in any particular HTML page.
    • In the HTML page, an id selector is applied to an HTML tag as an id attribute.
    • Here is an example of an id attribute (applied here to a paragraph tag):
      <p id="mainParagraph">

You can combine a class attribute with an id attribute like this:

  <p id="mainParagraph" class="normalText">

and the order of the two attributes is not significant.


You can even apply more than one class selector to an HTML element, like this:

  <p class="normalText highlightText">

(The above sample assumes that we have defined both .normalText and .highlightText class selectors in our stylesheet.)

Here is a sample of how you can apply more than one class selector to the same HTML element. This is page multipleClassSelectors.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>Multiple Class Selectors</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <style type="text/css">
    body { font-family: Arial, sans-serif; }
    .normalText { font-size: 1.7em; }
    .highlightText { font-weight: bold; font-style: italic; }
  </style>
</head>

<body>
  <p class="normalText">This paragraph displays in normal text.</p>
  <p class="highlightText">This paragraph displays in highlighted text.</p>
  <p class="normalText highlightText">This paragraph displays in both
    normal and highlighted text.</p>
</body>
</html>

You can see the above page displayed in a browser here.


You should note these points about how class and id rules are named and applied:

Note:  Most stylesheet references and tutorials mention a variation on the class selector that looks like this:
h3.blue {color:blue}
This type of class selector is technically referred to as being "bound to an element type" and is fairly common in the real world. You may use this type of class selector as much and as freely as you wish, but it can be limiting to an extent that you may find frustrating, because any class selector that you bind can only be used in that type of element. I prefer to use class selectors that are not bound, and which are called "free-range class selectors" because I can use them in any tag that I want to.


Inline Stylesheets

An inline stylesheet's rules are applied as an attribute of the HTML element (tag) that you want them applied to. This type of stylesheet can be applied to almost any HTML element, almost anywhere in your page's body. An inline stylesheet's rules look like this:

  <p style="background:#FFFF00; color:blue;">This is some text in a paragraph.</p>

You should note that the color property in this example refers to the color of the text that is contained by the paragraph tag. We will see other uses of the color property later.

One of the amazing and interesting aspects of inline stylesheets is that you can apply background colors to any part of your page without having to put the elements you want to give a background color to, inside a table as you would have to do with standard (non-CSS) HTML. For instance, you can give even a single word a different background color like this:

One of the <span style="background:yellow">amazing</span> and 
interesting aspects of inline stylesheets...

Please note that the <span>...</span> tag is used a lot to apply CSS rules to a page's content. The <span>...</span> tag was specifically designed by the W3C to enclose small portions of content, and to apply style rules to that content. Also note that a <span>...</span> tag does not add any linefeeds (line breaks) to the element/text that it contains.

As noted above, the rules in inline stylesheets are added to the rules in both an external stylesheet and an embedded stylesheet. If any rules in the inline stylesheets conflict with rules in the external or embedded stylesheets, the rules in the inline stylesheets override the conflicting rules in the external or embedded stylesheets.


Embedded Stylesheets

An embedded stylesheet is located in the <head> section of your Web page. Your <head> section might, for instance, look like this:

  <head>
    <title>An embedded stylesheet sample</title>
    <style type="text/css">
      <!--
      body
      {
        font-family:Arial,Garamond;
        color:blue;
        font-size:1em;
      }
      -->
    </style>
  </head>

You should note these points about the above code:


External Stylesheets

Some books and references refer to this type of stylesheet as a "Linked" stylesheet. As you will see in just a moment, the stylesheet is indeed attached to the page with a <link> tag, but I will go with the accepted terminology of the CSS specifications and will refer to this type of stylesheet as an external stylesheet.

This type of stylesheet is where the real power of CSS is applied to your Web site. You can format an entire Web site with a single stylesheet, as long as all of the pages in the Web site know where to find the stylesheet (which we'll see in just a moment). If you need to change the formatting of the site, you only have to change this one stylesheet, upload it to your site, and voila! the whole site reflects your change.

You make an external stylesheet by typing some style rules (declarations) in a text editor such as Notepad, DreamWeaver, or HomeSite. Then you save the rules as a text file with a file extension of .css. For instance, you could type these rules into Notepad:

  body
  {
    font-family:Arial,Garamond;
    color:blue;
    font-size:1em;
  }
and save these rules as file myStyles.css, for example. The file myStyles.css is now an external stylesheet.

There are some restrictions on what can go into an external stylesheet:

You should note carefully that the only things that can go into an external stylesheet file are rules and comments . There should be no HTML tags. This restriction means that you must not put a <style>...</style> tag into an external stylesheet.

Please note that CSS comments start with /* and end with */ .

The filename for your external stylesheet can be whatever you want to name it. But the extension must be .css, as noted above.


But now the pages in your site need to know where to find the external stylesheet. You tell your pages how to find the external stylesheet with a <link> tag in the <head> section of each page that you want the external stylesheet's rules applied to.

Here is what the <link> tag (in the <head> section) looks like:

  <link rel="stylesheet" type="text/css" media="all" href="myStyles.css" />

You should note these points about the above code:


Div, P, and Span Tags with CSS

The <div>...</div>, <p>...</p>, and <span>...</span> tags are among the most frequently used and handiest tags to use with CSS.

The <div>...</div> tag:

The <p>...</p> tag:

The <span>...</span> tag:


Contextual Selectors

Sometimes you need to limit the places where the browser applies your style rules. One way to do this limiting is to use what are called contextual selectors. A contextual selector is one that the browser applies in the context of another, specified selector.

For example:

  .first P { color: red }
  .second P { color: blue }

Contextual selectors consist of several simple selectors separated by whitespace. Only elements that match the last simple selector (in this case the 'P' tag) are affected, and only if the search pattern matches. In simple English, what this means is that when a page uses the selectors shown above, content that is contained by a P tag will be red, but only if the P tag is contained by a tag that has a .first class attribute in it; and the content will be blue, but only if the P tag is contained by a tag that has a .second class attribute in it.

The following example shows how the selectors shown above can be used. You can see the sample page here.

This is page contextualSelector.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <title>Contextual Selector Example</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <link rel="stylesheet" type="text/css" media="all" href="contextualSelector.css" />
</head>

<body>
  <div class="first">
    <p>
      This is the first paragraph.
    </p>
  </div>
  <div class="second">
    <p>
      This is the second paragraph.
    </p>  
  </div>
</body>
</html>

This is page contextualSelector.css:

/* Contextual Selectors */

.first P { color: red }

.second P { color: blue }

The CSS Box Model

The CSS box model describes the rectangular boxes that are generated for tags/elements in the page, and which are laid out according to the visual formatting model. The W3C has a fairly good explanation of this box model, which I will borrow from here.

Each box has a content area (e.g., text, an image, etc.) and optional surrounding padding, border, and margin areas. The size of each area is specified by properties such as border, padding, and margin; quite naturally; in elements such as <div>, <p>, and <span>.

The following diagram shows how these areas relate and the terminology used to refer to pieces of margin, border, and padding:

The CSS Box Model

The margin, border, and padding can be broken down into left, right, top, and bottom segments (e.g., in the diagram, "LM" for left margin, "RP" for right padding, "TB" for top border, etc.).

The perimeter of each of the four areas (content, padding, border, and margin) is called an "edge", so each box has four edges:

  1. content edge or inner edge
    The content edge surrounds the element's rendered content.
  2. padding edge
    The padding edge surrounds the box padding. If the padding has 0 width, the padding edge is the same as the content edge. The padding edge of a box defines the edges of the containing block established by the box.
  3. border edge
    The border edge surrounds the box's border. If the border has 0 width, the border edge is the same as the padding edge.
  4. margin edge or outer edge
    The margin edge surrounds the box margin. If the margin has 0 width, the margin edge is the same as the border edge.

Each edge may be broken down into a left, right, top, and bottom edge.

The dimensions of the content area of a box -- the content width and content height -- depend on several factors: whether the element generating the box has the 'width' or 'height' property set, whether the box contains text or other boxes, whether the box is a table, etc.

The box width is given by the sum of the left and right margins, border, and padding, and the content width. The height is given by the sum of the top and bottom margins, border, and padding, and the content height.

The background style of the various areas of a box are determined as follows:


Examples

The following sections of the handout will present a few examples of the kinds of things you can do with CSS style rules. The possibilities and combinations are almost endless, though, and you should experiment and play with these rules as much as you can! You can learn more about the various CSS properties at http://www.w3schools.com/css/css_reference.asp, which is a wonderful source of both HTML and CSS information.

For our purposes of being able to see the style rules along with the HTML tags that are affected, I will use embedded stylesheets in some of these examples. But you should remember that part of the power of CSS for your Web sites is in the use of external stylesheets, which I highly recommend and use for all of my real-world sites. :-)


Document Background example

Here is some code that controls the background of a document, and it looks like this in the browser . Make sure you scroll the text in the sample page, and note what happens (or does not happen) to the background image.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <title>Sample 1</title>
  <style type="text/css">
    <!--
    body
    {
      background:url(images/SantaFeStucco.bmp);
      background-attachment:fixed;
      color:black;
      font-size: 1.3em;
      font-family: Arial, sans-serif;
    }
    -->
  </style>
</head>

<body>
<p>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
<br/>
<br/>
This is a sample of how the background of a document can be controlled
with CSS style rules.
</p>
</body>
</html>


Font Properties example

Here is some code that controls the font properties of a document, and it looks like this in the browser .

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <title>Sample 2</title>
  <style type="text/css">
    <!--
    body
    {
      font-family:Arial,sans-serif;
      font-size:1.5em;
      font-weight:bold;
      color:blue;
      text-align:justify;
    }
    -->
  </style>
</head>

<body>
  <p>
  This is a sample of how the font of a document can be controlled
  with CSS style rules.  Please note that the text-align property is
  set to "justify".
  </p>
</body>
</html>


Character Entities and List example

You can use style rules to change the size and color of character entities. You can also change the appearance of lists. Following is some code that does both.

The sample page looks like this in the browser.

The HTML page is suitSymbols.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
<head>
  <title>Using Entity Shapes for Suit Symbols</title>
  <link rel="stylesheet" type="text/css" href="testShapes.css" />
</head>

<body>
<p>
The symbols for the suits of cards in an American
deck are:
</p>
<ul id="suitList">
  <li><span class="suitSymbols" id="hearts">&hearts;</span></li>
  <li><span class="suitSymbols" id="spades">&spades;</span></li>
  <li><span class="suitSymbols" id="clubs">&clubs;</span></li>
  <li><span class="suitSymbols" id="diams">&diams;</span></li>
</ul>
</body>
</html>

The stylesheet for this example is testShapes.css:

/* Style sheet for testing shapes */

p
{
  font-family: Arial, sans-serif;
  font-size: 2em;
}

.suitSymbols
{
  font-size: 3em;
}

#hearts
{
  color: red;
}

#spades
{
  color: black;
}

#clubs
{
  color: black;
}

#diams
{
  color: red;
}

#suitList
{
  list-style-type: none;
  list-style-position: outside;
  list-style-image: none;
}

Please note these points about the above code:


Table example

Here is some code that controls the appearance of a table, and it looks like this in the browser .

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <title>Sample 3</title>
  <style type="text/css">
    <!--
    table
    {
      border:double;
      border-color:red;
    }
    
    .left
    {
      background-color:#FFCCFF;
      font-weight:bold;
      font-family:'Times New Roman',serif;
      padding:3px;
    }
    
    .right
    {
      background-color:#B7B774;
      font-weight:bolder;
      font-family:Arial;
      padding:3px;
    }
    -->
  </style>
</head>

<body>
<table>
  <tr>
    <td class="left">
      Left-handed gloves
    </td>
    <td class="right">
      FREE!
    </td>
  </tr>
  <tr>
    <td class="left">
      Matching right-handed gloves
    </td>
    <td class="right">
      Just $99.95
    </td>
  </tr>
  <tr>
    <td class="left">
      Six-fingered gloves
    </td>
    <td class="right">
      A mere $333.50
    </td>
  </tr>
</table>
</body>
</html>


Border example

Here is some code that shows how you can use the CSS border properties, and it looks like this in the browser .

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <title>Sample 3</title>
  <style type="text/css">
    <!--
    #bordered
    {
      border: 10px dashed blue;
      background-color:#CCFFFF;
      padding:10px;
    }
    -->
  </style>
</head>

<body>
<div id="bordered">
  This text is in a &lt;div> tag that has a border and a background
  color.  There are many other interesting things that you can do
  with CSS style rules.  Experiment!  Have fun!  Become an expert!
  Become a millionaire!  (Disclaimer:  this statement is not a promise,
  but it sure is a dream!)
</div>
</body>
</html>


Liquid Layout example

The folks at Maxdesign have some really good information about the CSS approach to what is commonly called Liquid Layouts. It is possible, and much more complicated, to do liquid layouts with JavaScript, but by far the easiest way to do it is with CSS rules.

The best way to test the liquid layout page is to make sure the browser window that opens below is not in a maximized state, and to resize the browser horizontally. Watch what happens to the column widths.

The main concept of doing liquid layouts with CSS rules is to use percentages for the property values for text layout (usually, using <div>...</div> tags) for width and margin properties. Here is some sample html code with some columns of text built using three div tags (this is file liquidLayout.html):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
	<title>Liquid Layout</title>
  <link rel="stylesheet" type="text/css" href="liquidLayout.css" />
</head>

<body>
<div id="layoutInfo">
  <a href="http://www.maxdesign.com.au/presentation/liquid/" target="_blank">Liquid Layouts Info</a>
</div>

<br />

<div id="header">Header</div>
<div id="col1">Column 1</div>
<div id="col2">Column 2</div>
<div id="col3">Column 3</div>
<div id="footer">Footer</div>

</body>
</html>

Now here is the stylesheet that implements the percentage widths and margins (this is file liquidLayout.css):

body
{
  font-family: Arial,sans-serif;
}

#layoutInfo
{
  text-align: center;
}

#header
{
  margin-bottom: 10px;
  background-color: yellow;
  text-align: center;
}

#col1
{
  float: left;
  display: inline;
  width: 48%;
  margin-left: 3%;
  background-color: lightblue;
}

#col2
{
  float: left;
  width: 20%;
  margin-left: 3%;
  background-color: pink;
}

#col3
{
  float: left;
  width: 20%;
  margin-left: 3%;
  background-color: lightgreen;
} 

#footer
{
  clear: both;
  background-color: yellow;
  text-align: center;
} 


EM-Driven Layout example

The folks at Maxdesign also have some really good information about the CSS approach to implementing an ideal line length for reading.

The best way to test the ideal line length page is to change the default text size in the browser. In Internet Explorer 6 or 7, you can change the default text size with this sequence of selections:

  1. "View" menu item
  2. "Text Size" menu item
  3. Various setting selections
Watch what happens to the column width.

Researchers have determined that the best line length for reading is about 25 or 30 letters. At this width, the human eye most easily takes in the information in the line that it is reading, and most easily makes the transition to the next line.

The main concept of implementing this ideal line length for reading with CSS rules is to use EM units for the property values for text layout (usually, using <div>...</div> tags) for the width property. An em is defined as simply the current point size. For example, in 12-point type, an em is a distance of 12 points.

Here is some sample html code with a column of text whose width is 25 EM units wide (this is file EMDefined.html):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <title>EM-Defined Column</title>
  <link rel="stylesheet" type="text/css" href="EMDefined.css" />
</head>

<body>
<div class="centered">
  <a href="http://www.maxdesign.com.au/presentation/em/" target="_blank">EM-Defined Info</a>
</div>
<br />
<div class="easyRead">
 Lorem ipsum dolor sit amet, consectetur adipiscing elit, set eiusmod 
 tempor incidunt et labore et dolore magna aliquam. Ut enim ad minim 
 veniam, quis nostrud exerc. Irure dolor in reprehend incididunt ut 
 labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud 
 exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
</div>
</body>
</html>

Now here is the stylesheet that implements the EM units for the property values (this is file EMDefined.css):

body
{
  font-family: Arial, sans-serif;
}

.centered
{
  text-align: center;
}

.easyRead
{
  width: 25em;
}