Cascading Style Sheets

(Reading: We strongly suggest you read chapters 8 and 9 of Head First HTML with these notes.)

When HTML was first introduced, there were a number of tags whose purpose was just for formatting: for example, tags that center or switch to an italic font. With HTML version 4.0, such tags were made obsolete (though most browsers still support them), in favor of a formatting technique called Cascading Style Sheets.

Customizing Your Tags

When a browser is displaying a page, there is a step of reading a tag, such as <em> or <h1> and then determining what the results are to look like. (This is sometimes called rendering a page.) Each browser has a default way of rendering a tag. For example, most browsers will render the <em> tag by switching to an italic version of the current font. Most browsers will render an <h1> tag by switching to a very large version of the current font. There are several important points to make about this:

CSS Style Sheets

You can specify the style of a tag using a style sheet. These style sheets can be put in (at least) three different places:

  1. Inline Styles. These are specified in the tag itself.
  2. Document-Level (Internal) Style Sheets. These are specified in the <head> of a document, using a special tag.
  3. External Style Sheets. These are specified in a separate CSS file that is connected to the HTML file by the <link> tag. You saw an example of this previously, and if you view the source for this web page, you'll see another example.

Suppose that we always want <em> to be red. After all, em stands for emphasis, and what could be better emphasis than putting something in red? (FYI, using color is, in fact, a terrible idea, because some people are color-blind or even completely blind. We'll talk more about the issue of accessibility as the need arises throughout this course. You should always think about accessibility when you are designing a web page, because you want your page to be readable by anyone, not only by people with the same physical abilities, browser software, computer display, and network bandwidth that you have. Some websites are legally required to be accessible. However, for the purposes of this lecture's examples, let's suppose that using red is a sensible thing to do.) Let's look at the three ways to make <em> red:

  1. Inline Style. You use the style attribute of the tag to set the color property to have the value red and the background property to have the value white. (You should be reminded of the attribute/value idea in tags, but the syntax is different. With CSS, attribute/value pairs are separated by semi-colons, and the attribute ends with a colon.) Note that you should always pick both colors, in case the user's browser has specified a background color that matches your foreground color. Here's the example:
    this is an <em style="color: red; background: white">important</em> word
    
    results in

    this is an important word

  2. Document-Level (Internal) Style Sheets. You use the <style> tag in the <head> of your document to specify the style for the <em> tag once and for all:
    <style type="text/css">
       em { 
          color: red; 
          background: white;
       }
    </style>
    

    Later in your document, you just use the <em> tag normally, and it's rendered as red.

  3. External Style Sheet. These look just like document-level style sheets, except that you don't put the definition(s) inside a <style> tag. Instead, you reference the file using the <link> tag in the <head>, the same place you would use the <style> tag. Suppose we create a file called my-style.css that contains the following:
    em { 
       color: red; 
       background: white;
    } 

    and we reference it in the <head> like this:

    <link rel="stylesheet" type="text/css" href="my-style.css">
    

    As with document-level style sheets, we can just use the <em> tag normally from then on.

Syntax Note

There are several facets to the syntax of styles:

Exercise 0

Please do the first exercise described in this CSS Example

Exercise 1

Exercise 1

Create a small web page containing the following content:

<html> 
 <head>
  <title>Solution to Exercise 1</title>
 </head>

 <body>

  <p>This is the first paragraph of my little page.
  It should be green since
  we modified the style of the P tag.

  <p>Here's a <strong>second</strong> paragraph,
    and it uses the
  <strong>STRONG</strong>
  tag and also a
  <em>customized</em>
  EM tag.  We can also, just for fun,
  <strong> see what <em>nesting</em> elements</strong> does.

  <p>Here is the take-away message: you have power over
  presentation!

 </body>
</html>

Please do the following:

  1. modify the em tag so that it is red, using inline styles.
  2. modify the strong tag so that it is blue, and has a font-size of 200% (doubling the font size). Do this using a document-level style sheet.
  3. modify the p tag so that it is green, using an external style sheet called style.css
  4. Observe the effect of nesting in the modified em and strong in the second paragraph.

Cascading

CSS has “cascading” in the title because there's a strict hierarchy that determines which specification applies if the style of a particular tag is set in more than one place. Suppose you specified the <em> tag as green in an external style sheet, blue in a document-level style sheet and red in an inline style. Which wins?

The simplest answer is that the closest specification wins. This makes sense, because you can use the more local specifications to override the more distant, global specifications. So, inline style attributes beat document-level sheets, and document-level sheets beat external style sheets.

Furthermore, properties from enclosing elements can be inherited by the elements inside them. Notice how, in the exercise, the <em> element inside the <strong> element inherits the font size.

If you'd like all the technical details of the cascade, you can check the specifications of cascade order. The Head First HTML book also describes this in more detail than you probably want.

Which Style Sheet to Use?

One of the most common rules of thumb for creating clear and beautiful documents is consistency. For example, section headers should always be the same size, weight and font. Indeed, this is what a “style sheet” means in the context of document processing. MS Word format files are the same thing.

You can best achieve consistency by specifying the style far enough from the text so that the style is specified in just one place. If you have a single web page that you would like consistent, you should use a document-level style sheet. If you have several web pages (a web site) that you want to be consistent, you should definitely use an external style sheet. Even if your website is only a single web page but you think you might someday have a second web page using the same style, you should use an external style sheet. In short, always use an external style sheet.

In this course, you and a partner will be creating a website for a client. For that website, you should define an external style sheet. Then, if you or your client decides that <h1> should be centered, <h2> should be bold and blue, <h3> should be underlined and non-bold, and <em> should be pink, you can do that in one place. If you later change your mind and decide that <em> should be purple, you make one change in one file and all of your website is consistently and instantly changed. If you had used the local style technique, you would have to edit every page of your site, searching for and modifying each occurrence. This is tedious and error prone.

Because the CS110 faculty would like our (very large) course website to be consistent, we will be using a CS110 style sheet throughout. (But we may not have fixed all the web pages yet; we're migrating from a non-CSS website. Please point out any errors that remain.)

We will often use inline styles and document-level style sheets for examples because it reduces the number of files to edit in order to show something, but in practice you should almost never use these. (Indeed, the Head First HTML book never uses inline styles at all.) We will show you some techniques that allow you to get the same effect as an inline style or document-level style while retaining the ability to keep all style information in an external file.

The Bigger Picture

The idea of CSS illustrates an important concept in the field of computer science, namely abstraction. Abstraction is the idea of saying what you want done without saying how to do it. By leaving out the details about how to do something, you allow for some flexibility, so that you can revise your method of doing the task without messing up anything that depends on that task being done. Here, we said <em> without saying what that meant, putting elsewhere the specification of how to emphasize.

SPAN and DIV

So far, we've achieved an effect by modifying one of the existing tags, mostly <em>. Suppose you want to make some text a different color, but it's not emphasis, so it feels wrong to use the <em> tag. As another example, in the title of the color lecture we used several colors of text (just to be cute). How did we do this using CSS? The answer is a new tag called <span>. By itself, <span> does nothing. Its only purpose is to support the style attribute so that you can modify the appearance of the stuff between start and end <span> tags. It's a pretty intuitive name for the tag. If you view source, on the color lecture, you can see how we did this.

Suppose that we're using a special word and we want just that special word to be rendered differently. We could say:

The word <span style="color: teal; background: white">
    Supercalifragilisticexpialidocious </span> 
is a special word

and the result would look like:

The word Supercalifragilisticexpialidocious is a special word

Thus, we don't have to press <em> or <strong> into a job they're not suited for; we can just use <span> whenever we want to modify the style of something.

This is an important point, so we want to bring it out: The purpose of the HTML tags are to convey the structure and meaning of the content of your site, so you do not use <em> for something other than emphasis. Only use a tag that conveys the correct meaning of its contents. For example, don't use <h1> just to switch some text to a big font; reserve it for something that is a header, indeed, the major header.

<span> is intended for stuff within a paragraph, so when you use <span> there is no break in the paragraph. If you want to start a new paragraph, you are probably defining some big division of your document and you should use the <div> tag. For example, you might be defining the appearance of the abstract, the bibliography, a theorem, a glossary entry, or an exercise. For that purpose, you can use the <div> tag. Like <span>, it exists primarily to carry a style sheet. (There are other uses that we'll omit.) The difference is that div is a display object, meaning that using it is separated by vertical space from the preceding and following material, like a paragraph.

Custom Markup

There is an important pitfall in using <span> and <div> this way. Suppose we are creating a web page that involves a number of special terms. Maybe they're trademarked terms, for example. If we use <span> each time they occur, we can control how they look, but if we later change our minds about the presentation, we'd have to go back and find all occurrences and change them. This is just the thing that CSS should solve.

We want to set these special terms off somehow, but we don't want to use <em> or <strong> or even <dfn> (there is such a tag, used for terms you are defining). We wish there were a tag called <tm>, but there isn't. If there were, we could modify the style for <tm> and use that.

One option is to use style classes. For example, in our document-level style sheet we could write:

<style type="text/css">
 span.tm { 
    color: maroon; 
    background: white 
 }
</style> 

Without the surrounding <style> tag, the specification of span.tm can also be placed in an external style sheet. Within the document, we can write:

Remember that
<span class="tm">Coke</span> and
<span class="tm">Pepsi</span> are both registered trademarks.

With the result looking as we want:

Remember that Coke and Pepsi are both registered trademarks.

If we later decide that instead of maroon, all the trademarked items should be red or even black (so that they no longer stand out), we can again change this in just one place.

Note that we defined our class by what the item is, not what it looks like. The code of our document is only about the content, not the appearance. Appearance information is only in the style sheets. This separation of content from appearance is an important aspect of the concept of abstraction, which we discussed earlier.

Consider the alternative. Suppose that instead of defining a class called tm for our trademarked terms, we defined a maroon class and used that. If we later changed our minds and decided to make them pink, we'd have the bizarre result that the class named maroon makes things pink. Read more about good class names.

The CS110 web pages use <div> and <span> in this way, using the ex class, to define the format for exercises in these lecture notes. View the source to see the markup tags.

You can use classes to modify the presentation of any tag, not just <span> and <div> . For example, you might have certain headers you want to be different from other headers, say appendices or optional sections. You can then define classes such as:

H2.appendix { ... }

H2.optional { ... }

H2.preamble { ... }

You would use these in your HTML file like this:

<h2 class="optional">Obscure Connections</h2>

<h2 class="appendix">Bibliography</h2>

Here is how the section classes might look.

Exercise 1.5

Please do the second exercise described in this CSS Example

Exercise 2

Exercise 2

Return to your small web page from exercise 1 and do the following:

Syntax Note

There are two facets to the syntax for defining and using style classes:

Debugging CSS

As we get to more complicated CSS, debugging it can sometimes be very difficult, as the layout rules can be a little unintuitive. Fortunately, there are some tools that can help.

The first tool is the browser's error console. Whenever a browser encounters something it doesn't expect or doesn't understand, it generates an error message. However, it hides those error messages from the human user, since 99.99% of people viewing the website aren't developers and don't care about errors. But you're a developer and you care, so look for the error messages.

In Firefox, look under Tools > Error Console.

The next tool is the HTML and CSS validators. Don't try to debug invalid code! Make sure it validates before struggling to get it to behave properly.

Finally, there's my favorite: Firebug. Firebug is is a plugin for Firefox. Get it, use it, enjoy it. It's awesome.

Caches

One of the great advantages of external style sheets is also, for a web developer, a slight bother. To understand that, you have to understand caches.

The word “cache” (pronounced “cash”) is an ordinary, but uncommon, English word (more of an SAT word for most people). However, it's used all the time by computer scientists because caches are used all the time by computers, in all kinds of ways, because caching is a general technique for speeding things up.

In particular, your web browser will cache (keep a copy of) an external style sheet in a folder on your local machine (that folder is called, of course, the cache). If the web browser needs that style sheet again, say on another page of your site that uses the same external style sheet, the browser doesn't have to re-download the file; it just grabs a copy from the cache. This makes the web browser faster.

So, why is the browser cache a problem for a web designer? Because if you make a change to the external style sheet, the web browser may continue to use the old cached copy, instead of getting the new improved copy from the server. This means that when you view your page, you won't see your changes — very frustrating.

The solution is to tell the web browser to ignore the cache when you re-load the page. In most web browsers, this is done by holding down the shift key when you click on the reload icon.

So, just remember:

When in doubt, use shift+reload

ID versus Class

Students often wonder about what the difference is between a class and an id, and when to use each one. The key is uniqueness: an id must be unique, while a class describes a kind/type/category of element.

For example, there might be many occurrences of these classes of elements:

On the other hand, there is probably only of the following elements per page, so these might have an id.

The uniqueness of an id makes them suitable as the fragment in a URL, so you can link to that particular element of a page.

Here's a picture showing an id being used once and a class being used thrice. Also note the syntax: pound signs for ids and periods for classes.

figure showing an id used once and a class used thrice

Please inspect the following two examples of classes and ids, one using students and the other using faculty. Use Firebug on them!

Examples of CSS Customizing

Here are some examples of using CSS to customize a tag.

Learning More

We have only scratched the surface of CSS. There is much more to learn, and we'll learn some more in a future lecture. You can also teach yourself more from

View another example of the application of basic CSS concepts to the styling of a simple web page about introductory CS courses.

Some additional CSS examples were created by Lyn Turbak.

Be amazed by CSS Zen Garden

To be horrified, check out WebSitesThatSuck.com

Solutions to Exercises