CSS Validation DOCUMENTATION   |   CSS TUTORIAL   |   FORUM

CSS Tutorial - Start Learning Cascading Style Sheets

This tutorial is designed to be brief, robust, and self-explanatory. These concepts and methods are presented as they are because there are certain standards and recommendations for building proper CSS. You'll learn the various rules associated with coding style sheets. Certain assertions will be made that may not be cited directly. In any case, the W3C is a definitive source. You should have a knowledge of (X)HTML before attempting the tutorial. It looks long but you can do this tutorial in less than an hour. Now then, let's begin.

What CSS is and does

CSS stands for "Cascading Style Sheets". They're considered "cascading" because they can build from each other, and each indivual element of it can manipulate itself based on the configuration of your structure. Then they are what it says: "style sheets". They define the literal style of your webpage.

Style sheets control the colors, placement, alignment, fonts, text sizes, and other things on your web page. You can see how the style sheet for this site affects the colors of the links you see and the width and fonts of the content.

If you're an HTML veteran, you probably are familiar with <font> tags. Well, brace yourself: they're not used in XHTML 1.0 Strict or XHTML 1.1 documents, and shouldn't be used again. It is just one example of a tag that is dying because CSS is replacing its job in modern websites, especially AJAX-powered ones. This is the vital role that CSS plays. Unfortunately, CSS doesn't play well with others, so there are some rules.

The Rules

Rule #1: Separate content and structure from presentation.

Let's just say that CSS is friendlier if it's not surrounded by any of its HTML bullies. Modern browsers and websites demand a clean, pure, and modularized solution. You'll find this an absolute requirement when developing a functional AJAX web application, because CSS does more than just give your links pretty colors. It is crucial in the design of Javascript-powered web applications.

So none of this! <a href="page.html" style="color: red;">My link</a>   No! And certainly not this: <a href="page.html"><font color="red">My link</font></a> (That's not even valid Strict or 1.1 markup.) So for now, you need to assume that you absolutely will not embed CSS into your HTML or XHTML document! Okay, whatever. There are some exceptions. But they're rare. You'll see one of them in the source of this page.

Rule #2: Kiss it: Keep it simple, stupid!

CSS is made to be simple. There's no reason to over-complicate things. It doesn't have much of a brain be more compatible with browsers if the CSS you employ is done so simply.

Rule #3: Be consistent in your terminology, conventions, and casings.

Why would you call something a "wheelchair" then later call it a "wheelChair" or a "wheel_chair"? It doesn't make much sense to be that confusing or inconsistent with your CSS definitions either. Come up with a system and stick to it.

Rule #4: If you get lazy, so will the browsers.

If your CSS is embedded in your markup, declared in the header of your page, and is also in its own file (in other words, putting it wherever you want or is easiest), you're asking for trouble. All browsers do not render the same. Even Chrome and Safari -- although both using Webkit -- render with slight differences, and your CSS will be difficult to maintain and keep valid if you're lazy at first.

Rule #5: Hacks are bad (if you get caught).

Technically, if the CSS is W3-Standards-Compliant ("valid"), then the CSS is "good". But if there's that one thing you couldn't do without a cheap trick, is it really "good" CSS? Chances are, there's a better way to deal with it. (Unless you're compensating for Internet Explorer's flaws, which is totally understandable.)

"Getting caught" with a hack means either a purist looked at your code and found you using it, or something changed and now you can't figure out why the heck it's broken. You may also paint yourself into corners depending on how much relies on that one trick: probably more than you think. Because browsers and even CSS aren't perfect yet, you may use CSS hacks as long as they're applied properly.

Finally: How to begin writing your style sheet

This isn't a website design tutorial so we won't review the steps to laying out your site. With all the pieces ready to go, your first step may not be what you're used to.

1. Create a new, blank (CSS) file.

Don't make your markup file yet! Start with the rudiments of your website's style by making the CSS file first. For the scope of this tutorial, all of our site's style sheet is contained in this file. In larger projects or sites with multiple themes, it's customary to create multiple CSS files based on type of content or one containing the entire theme. It's really convenient that way.

Okay -- go! You can use Notepad, but if you already develop websites you should have an editor with syntax highlighting. If you don't, get one.

2. Specify markup elements ("selectors").

Since you're styling markup, the style sheet accepts blocks of styling attributes which are headed by the selector string of the element you are styling. You can style everything from an entire tag, to just a few tags of that name or type, or a single specific tag with a given ID.

After your selector, you open the block with a curly brace denoted { and you will close with another curly brace } on the next line. The actual styling will be specified between those braces. Here's an example of an empty block styling all the <p> tags in a document that uses this style sheet: p {
}
Be sure to save the style sheet. Give it a .css extension. With only one style sheet, it might be best to just call it "style.css".

3. Connect your markup to the style sheet.

Your HTML page needs to talk to the CSS file somehow. There are several (convtorversial) ways to do this. The method explained here is by far the most standard and safest way to include a style sheet. You'll be using a <link> tag in your HTML page's <head> area. The most valid form of this tag is probably this: <link rel="stylesheet" type="text/css" href="style.css" /> Note: If you're not validating for XHTML, remove the / at the end. Of course, replace "style.css" with the path to or file name of your style sheet.

4. Add some styling elements ("attributes") to the blocks.

Now let's add some color to the text of the paragraph tags! You add style attributes inside the block like so: p {
   color: #CC0000;
}
You can, theoretically, have as many attributes as you want: p {
   color: #CC0000;
   line-height: 1.5em;
   padding: 10px;
   background: #EFEFEF;
}
Now would be a good time to take a break and at least learn the common attributes so you have so you aren't totally lost, but it's pretty easy to get the basic idea just by looking at them, right?

That's the crux of the basics of CSS. You can now manipulate all your tags of various types. Let's learn how to specify which specific tags get styled.

5. When needed, create classes and IDs.

You can probably start writing your markup now. When you notice that you want to style only particular <p> tags, for example, then you need to know how to use classes and IDs. They're powerful and should be able to integrate with Javascript/AJAX applications rather easily. In fact, Javascript knows which HTML elements to manipulate based on their CSS classes and IDs. That's why this is so important.

A few really important definitions:

Class
In CSS, this is a way to select a group of related tags. They may or may not be the same type of tag.
ID (Identifier)
In CSS, this is how you specificy one very particular tag and only one.
Case-sensitivity
CSS is case-sensitive! This means that "something" is not the same thing as "SomeThing"! This can really trip you up if you aren't careful.
Term
In CSS, we define a term to be a single specific selector. You'll learn about those in a few minutes. Terms are separated by commas, but a single term may have spaces in it.

If you wanted to apply certain styles to only specific <p> tags that you specify, you can give them their own class by adding a period . to your selector and appending a class name of your choice: p.Something {
   font-family: sans-serif;
}
To apply these characteristics to a tag, you can add the "class" attribute to your HTML markup: <p class="Something">My paragraph</p> And because it's a class, you can apply that to as many <p> tags as you want. But what if you wanted those same styles to be able to go to more than just various <p> tags? Easy. Remove the tag specifier: .Something {
   font-family: sans-serif;
}
Now you just have a period and then the class name. Now you can add class="Something" to almost any HTML tag you want and it will obtain those attributes. When you refer to classes, we may say that a tag has a certain class .Something applied to it (with the period).

What's all the fuss about IDs (identifiers)?

Suppose you wanted to style a tag. A very, very particular tag. It's such a special tag, in fact, that there's only one of its kind for the entire page. In this case, you should assign it an ID. This ID will be unique to it and no other DOM element. By way of example, the title of each page on this site ("CSS Validation") is styled via CSS identifiers. Take a look at the source!

In CSS, IDs are denoted by the pound # symbol. In HTML, you'll add an "id" attribute to your tag. Let's take a look at some CSS that styles a particular tag: p#pageTitle {
   font-weight: bold;
   color: blue;
   letter-spacing: 0.2em;
}
Now we have some styling that will apply only to a particular tag which has a specific name! Like with classes, we can allow this to apply to any type of tag by omitting the type of the tag: #pageTitle {
   font-weight: bold;
   color: blue;
   letter-spacing: 0.2em;
}
As you'll read in a moment, you can only apply this to one very specific tag anyway, so why specify a tag in the CSS? Well, truthfully, it doesn't matter. You can be more verbose and comprehend it better, or you can leave it off to be more flexible. (Suppose you didn't always use a <p> tag for that particular content?)

Now we can link this ID to an HTML tag in our markup: <p id="pageTitle">A Paragraph Title</p> Notice how the ID starts uppercase. According to our CSS Proper Conventions Guide, IDs always are camel-cased with the first letter being lowercase. It's a practice that carries over from good object-oriented programming because, often, Javascript/AJAX applications will want to interact with our document object model (DOM). This is when IDs become very important, and need to be easily distinguished from classes in which we leave the first letter lower-case, but camel-case the rest of the name.

It's important to note that you can really only have one particular tag on a given HTML page with the same identifier. If your DOM has more than one tag with the same ID, there will be problems.

Getting nitty-gritty: More complex selector strings

Commas: Spanning your style

Often, you will need to style different types of tags, some with classes, some just given an ID, some neither, the exact same way. You can span a block of style across multiple elements by separating the element selectors with commas: a, span, p#pageTitle, .ThisToo {
   font-style: italic;
   color: rgb(232, 121, 0);
   line-height: 150%;
   background-image: url("images/background.gif");
}
Now, any HTML elements <a>, <span>, <p id="pageTitle">, and <div class="ThisToo"> will inherit these characteristics.

As you will soon see, commas are the ultimate selector string divisor because they absolutely separate more specific selectors (called "terms").

Spaces: narrow your style

Just as commas make your style more expandables, spaces in a selector string make the style block more specific and narrow. Suppose you have this HTML (for some crazy reason): <p>
   <div>
      <h1 class="PageTitle"><span>My</span> Title</h1>
   </div>
</p>
You can access any group of nested elements by separating them with a space in your selector. So in order to access that trippy span tag in there, you could do this: p div h1.PageTitle span {
   color: #003366;
}
You should realize that the entire selector string for that block is actually one term even though it has spaces. In CSS, selector terms are separated by commas, not spaces. This means you can still "span your styles" with something like this: #myID, p div h1.PageTitle span, a, span.Something {
   color: #003366;
}
This is an impractical example, but it conveys the concept. Those spaces narrow down the selector to a specific set of elements nested within others.

Colons: Pseudo power

Put your mouse over this link. It changes color. Cool! Yeah, it's pretty... thanks. Here's the CSS that did that: a:hover {
   border-bottom: 1px solid #CC0000;
   color: #5D5D5D;
}
This selector has a colon : in it. It's applied to an "a" selector. Pending browser compatibility, this can be used on almost any type of markup tag. It's called a "Dynamic Pseudo Class".

The other dynamic pseudo classes inculude :active and :focus. One other you might use often is :visited, but it's not dynamic.

Commenting your CSS

Before we finish, let's go over comments real quick. Comments can be inserted to your style sheet which will not be read by the browsers or Javascript. The comments are only for human convenience to make notes and annotations to the style. You start a comment with /* and end it with */ like this: /*
 For any elements that should be centered.
*/

.Centered {
   text-align: center;
}
The comment can be on one line or span multiple lines. Make comments brief, helpful, and non-obvious. (Above is, admittedly, a poor example.) They're especially useful when using strange CSS tricks that aren't intuitive.

The Extended CSS Tutorial

That concludes the first tutorial. The sequel to this is currently being written and will cover more advanced, yet general, CSS topics. With the material covered in the scope of this tutorial, you should be able to design a complex website with careful work. The advanced CSS topics are more commonly used in Javascript applications.

At this point, you may want to learn the CSS attributes you can add to your style sheet in addition and more detail to the ones shown here. It might also be a good idea to review the CSS Proper Conventions Guide so you can make your style sheets more conservatively.

Happy CSSing!