Top Nav

Your how-to site for community journalism

Cascading Style Sheets (CSS)

From the beginning, HTML has always been perceived as a very simple “language” to learn.  With only a few simple tags, you could mark up a document and put it online.  HTML was very forgiving, flexible and intuitive.

However, this same simplicity was HTML’s biggest weakness. You could easily make a headline, add an image, make a list, or create a form. However, you had no control over how that content would look once a visitor to your site called it up. Tables would resize themselves willy-nilly depending on the browser being used, and fonts and colors were difficult to standardize and even harder to go back later and change.

In order to assert some control over how a page would look for all visitors, there either needed to be a complete overhaul of HTML or an alternative, parallel system of style control (control over the display of a document, as opposed to the internal structure of a document).  Guiding this system was a strong concern that the user be able to display web pages on a wide variety of devices — readers for the blind, handheld devices, TVs, printouts, and more.

History

Cascading Style Sheets was one of several solutions, and they have been around for a long time in web years. In 1996, CSS 1.0 became a full recommendation of the World Wide web Consortium (W3). [http://www.w3.org/Style/LieBos2e/history/]  But agreement on, and adoption of, CSS in browser software has been a slow and complicated process.

Cascading Style Sheets — even the name sounds a little intimidating, like perhaps you’re falling down a steep slope.  But the name is just an accurate description of what CSS is — “sheets” (pages or chunks) of code that describe the style of a document in such a way that multiple commands “cascade” — in other words, they’re applied in a certain order that ensures that both the user and the page designer get as close to the same effect as they possibly can.

Basic Overview

Many tutorials start with an overview of the language, but the best way to appreciate CSS is to see how it works. With CSS, you can take a very simple HTML document and make it appear in exactly the way you’d like.  First, let’s start with a basic HTML document:

<html>
<head><title>CSS Demonstration</title></head>
<body>
<h1>How to Carve a Turkey</h1>
<p>By Travis Smith</p>
<p>If you’re going to carve a turkey, there are several things you must have.</p>
<ol><li> a cooked turkey</li>
<li> a sharp knife</li>
<li> a clean cutting board</li>
<li> a large fork</li>
</ol>
<p>Questions? Visit our <a href=”comment_form.html”>comment form</a>.
</body>
</html>

You can click here to view it.

When you view this document now, you can see it is styled with the font size and type you have chosen for viewing with your browser.

Using CSS, you can quickly establish uniformity over the document’s look.  Let’s quickly improve the document by creating a second file, a CSS file, and putting these lines in it:

body {
font-family: verdana,arial,sans-serif;
font-size: 14px;
line-spacing: 2em;
}

h1 {
font-size: 300%;
color: #6666FF;
font-weight: normal;
text-align: center;
}

ol {
text-indent: 2em;
list-style-type: upper-roman;
}

.byline {
font-style: italics;
font-variant: small-caps;
}

(Don’t worry, we’ll explain all this code as we go through this section. For now, just bear with us.)

Now, we add one more line to the HTML file that tells it to use the styles from the CSS document.  That line goes in the HEAD of your HTML document, and it looks like this:

<link rel=”stylesheet” href=”sheet1.css”>

Now, click here to see the results. With the exact same HTML (except for the addition of the link to the style sheet, of course), the page is now styled with CSS and a significant transformation has occurred.  Let’s go through that CSS step-by-step and see what happened.

The Style Tag

You can put style codes directly into an HTML document with the <style> tag.  Usually, though, we don’t recommend it because it defeats the purpose of using styles — if you define them anew in each document, you aren’t really creating a consistent, easy-to-update set of rules that apply to your whole site.  But if you’d like to see an example of the same document with an embedded stylesheet, click here.

Our beginning CSS file has four rules in it. Each rule describes what to do about a particular part of an HTML document. The first rule contains instructions about the BODY element.  It says, for anything within the BODY tag (in other words, for everything displayed on the web page) use the “Verdana” font, at 14 pixel size.  Space the lines out double (“2em” means space the lines twice the height of a regular line of text).

The second rule describes how to display any H1 (the largest sized headline) element.

By default, a browser will display H1 elements at about double regular size, but we’re overriding that and telling the browser to use a size that’s 300% of the standard size. (Standard size is, according to the first rule, 14px.) We also change the color of all H1 elements to blue.  [Learn more about HTML colors here.] Usually, H1 also makes text bold, but we explicitly make it normal and also set the text to be centered within the body of the document.

The third rule takes OL, the tag for an ordered list, and indents it using Roman letters instead of the usual 1,2,3,4.

The fourth rule is a little more specific.  Instead of changing an existing tag, we’re creating a rule for a “class” of elements by putting a period (“.”) in front of the rule.

In our HTML, you can see that one paragraph (“P”) is described as ‘class=”byline”.’  You can apply any class name to any element and then refer to elements of that class using CSS.  For example, you could say <li> to specify the “class” of an element in a list or <h3> to specify the class style in a middle-sized headline.

By defining a class style, you can easily and logically structure your documents and apply formatting exactly to the parts of the document that need them. In this case, we’ve made the byline appear as small capital letters, displayed in italics.

Now it’s true that we could have gotten most of these effects using straight HTML. But imagine that your site has hundreds or thousands of articles. Let’s say you decide you’d rather not have the bylines in italics. Instead of having to change all those files one by one, you can change the display of your bylines just by changing the CSS file and you won’t need to touch the HTML code at all.

CSS Structure in Detail

That’s the power of CSS. Now, let’s take a closer look at the parts of a CSS file. We’ve already said that a CSS file is a collection of rules. Each rule defines how to display some portion of an HTML document. Here’s a pretty basic rule:

H1 { font-size: 300%; color: #6666FF; }

A rule consists of a selector (the part outside the curly braces that says what parts of a document will be affected) and a declaration block (which is the part inside the braces that describes what to do with the thing that’s selected).

A declaration block should contain at least one declaration, which is a property (like font-size) and a value (like 300%) followed by a semicolon.  For the most part, spaces don’t matter in CSS. So, for example, the H1 rule above, and the one below are the same:

H1   {
font-size:  300%;
color:       #6666FF;
}

Semicolons: Always a Good Idea

The rules for CSS say that the very last declaration does not need a semicolon, because there’s a curly brace there to end the block.  But it’s guaranteed that later you’ll come back, add another rule at the end of the block and then wonder why your CSS isn’t working.  So always use a semi-colon.

If you have a mistake in any part of a declaration, the entire declaration is bad and that might spill over and affect other declarations or even rules. Here are some WRONG examples:

H1   {
font-size  =  300%;
color:       #6666FF;
}

In this example, the use of “=” instead of “:” after “font-size” means that not only does the “font-size” declaration not work, but the “color” property gets attached to the “font-size” property like one run-on word, so it’s broken, too.

P { text-align: right ;
H1   {
color:       #6666FF;
}

In this case, the missing right brace before H1 means that the whole H1 rule is going to fail – the P rule (for paragraph) doesn’t end until there is a right curly brace (“}”) inserted after H1.  This might be really frustrating to track down because the H1 won’t work while the P seems to be displaying just fine.

Selectors

We’ve discussed two kinds of selectors: element selectors (like P and H1) and class selectors (that start with a “.”).

Elements are easiest to remember as existing HTML tags.  So you can redefine the behavior of, say, the <B> tag and make it also be red, or underlined — though this might end up causing come confusion for people who don’t know about the special CSS rules on your site.

Class selectors are added to HTML by way of the “class” attribute. So above, we had a tag that looked like this: <p> and in the CSS document, we defined the byline class with a rule that started like this: .class {

There are a few more, and they can interact in really useful ways.

There are ID selectors

#nav {
text-align: right;
width: 150px
}

The difference between class and ID, other than the obvious “#” vs. “.” is that an HTML page should only have one of each ID, while it can have many of each class.  So if you had a class that was “subhead,” you could use it several times, but if you had an ID called “footer,” you should really only use it once, like so:

<p id=”footer”>Copyright 2005</p>

Remember also that the name of the class or the ID in the HTML does NOT include the “#” – that’s only used in the CSS to define the rule.

You can combine selectors easily for powerful results.  You could have a rule that made links in the navigation a different color than links in the document overall, like this:

A        { color: #45FF45 }

.nav A { color: #6666FF }

In a nutshell, this says that A elements (that is to say, links) are generally green, but if they’re within a class that’s called nav, they should be blue.

You can also do this with elements:

LI B { font-size: 16px;}

This says that any bold tag used within an LI tag (which creates an element in a list) will cause that text to become 16 pixels large.

Yet More Selectors

Finally, there’s a whole set of selectors called pseudo selectors. A pseudo selector is a selector that matches a part of an HTML document based on something that’s not explicit in the HTML.  The most obvious of these are the :link, :visited, :hover selectors:

A:link { color: green }

A:visited { color: black }

A:hover { color: blue }

Obviously, you don’t specify in the HTML whether a link has been visited or not – that’s something that the browser determines.  Ditto for hover – you don’t know when or if your users are going to put their cursor over a link.  So a pseudo selector describes a style for a part of the document that may or may not exist. In this case, you’re saying that general links are green, visited links should be black, and a link should turn blue when you hover over it.

You can use :hover with any element or property:

A:hover { color:red; text-style: italics }

This will make any link element turn to red italics when you put your cursor over it.  Click here for an example.

There are many other pseudo selectors, and with them you can create drop caps, indent first lines, select and format only certain tags, and more.  Using all these types of selectors, alone and in combinations, you can exert some truly remarkable control over the display of a basic HTML document.  If you want to learn more, check out the resources listed below.

Grouping

One of the things that makes CSS a little more confusing than HTML is that, in the interest of making it efficient to write and download, you can group selections to define them all at once.  So, for example, you can do this:

OL, UL, P, FORM, TABLE {
margin-top: 8px;
margin-bottom: 8px;
margin-left: 8px;
margin-right: 8px;
}

This sets an eight-pixel margin on all sides of those five elements (ordered list, unordered list, paragraph, form and table) no matter where they appear in the document. For even more efficiency, you can write this:

OL, UL, P, FORM, TABLE {
margin: 8px 8px 8px 8px;
}

or even this:

OL, UL, P, FORM, TABLE {
margin: 8px;
}

Each of these will apply an eight-pixel margin to all sides of each of the selected elements.

Cascading

You knew there had to be a reason it was called “cascading,” right?  Well, let’s look at the previous rule:

OL, UL, P, FORM, TABLE {
margin: 8px;
}

Click here to see this rule in action on the sample document.

(sheet2.css)

Now, to see the cascading effect, let’s add one more rule to the bottom of the CSS document:

P { margin-left 30px; }

You’ll see that the later P rule overrides the higher P rule. There are many, many ways that one rule can override another. Here are a few:

  • Later declarations in a rule override earlier ones.
  • Later rules override earlier ones.
  • If you have multiple style sheets linked from an HTML document, the last one takes precedent.
  • If you put style rules directly into your HTML document, that takes precedence over rules from a linked sheet.
  • “Class” rules override “tag” rules – so, for example,  “.byline” would be more authoritative than a simple “P” rule, regardless of where the rule is defined.

With all these (and several other) comparisons determining which rules take precedent, you can see why CSS can turn into a complicated mess. On the other hand, a logical set of CSS rules can actually help keep your site HTML organized. So it makes a lot of sense to learn CSS.

Dreamweaver

The current version of Dreamweaver, Version 8, has excellent CSS handling. Some of its CSS features:

  • It helps you determine which style rules apply to any particular part of your HTML page.
  • It keeps all the various possible properties at your fingertips so you don’t have to guess or have them memorized.
  • It can easily swap between different CSS documents and let you see the changes on screen immediately.

If you’re trying to modify CSS, especially complex CSS, Dreamweaver can be well worth the cost.

The Dark Side of CSS

CSS sounds like the answer to all your HTML problems, doesn’t it? You simply make a basic HTML page, then use CSS to lay it out exactly as you envision it. Alas, this is far from the truth.

The problem is that Internet Explorer, Netscape and Safari all have different, sometimes conflicting interpretations of the CSS standard. CSS is currently at version 2.1, and there’s a version 3.0 proposed, but even now, not all browsers correctly implement all of CSS 2.0. As you start to use CSS, it becomes absolutely critical that you test in every major browser that visitors to your site may use.

Browser Statistics

Current statistics, as of winter 2009, show Internet Explorer and Firefox as having about equal market share with about 45% each. Chrome, Google’s new browser, already has almost 4%, even more than Apple’s Safari (3%).

http://www.w3schools.com/browsers/browsers_stats.asp

Using CSS, you’ll definitely find that things that look OK on one screen look too small, too wide, too dark or the wrong font on another browser.  You’ll then discover that either you’ve made a mistake in your CSS, or that you need to go looking through one of the many CSS resources.

Resources

CSS spec at the World Wide Web Consortium (W3)

Start with the W3′s guide to CSS.  The information here is straightforward, clear and a good base for beginners – rare for a technical site.

http://www.w3.org/Style/CSS/

CSS Zen Garden

If you look at the source code of this site’s home page, you’ll find very plain, straightforward HTML.  By clicking the links on the side of the page, though, you can completely transform the look and feel simply by switching the CSS.  It’s an instructive – and inspirational – example of CSS in use.

http://www.csszengarden.com/

Position Is Everything

This site has a big catalog of the bugs in CSS that you may have stumbled across and the ways to work around them.  The thing about CSS bugs is that there’s almost always a way to defeat them. Other people have spent hours or days figuring out how to make a page like yours work in every browser, and the secrets are often listed at this site.

http://www.positioniseverything.net/

Eric Meyer CSS

No description of CSS would be complete without a mention of Eric Meyer. He’s written several excellent books on CSS – one’s an authoritative reference; others are how-to books that outline specific techniques for getting the most out of CSS.

http://www.meyerweb.com/eric/css/

Next Section

Powered by WordPress. Designed by Woo Themes