Cascading Style Sheets (CSS) Tutorial

Introduction

This article is a tutorial guide to getting started with Cascading Style Sheets (CSS). Its aim is to get you familiar with the basics of CSS, as applied to HTML-based web pages, and to give you the background you will need for further reading. If you have any suggestions or comments about this tutorial, please contact Poplar ProductivityWare.

To get the most out of this tutorial, you should already be familiar with the HTML language, and know how to edit (using a plain text editor), save, and view an HTML web page. In particular, you should understand the meaning of the HTML term element (an HTML element consists of an opening tag, such as <P>, followed possibly by some text and a closing tag, such as </P>). You should also be familiar with the basic structure of an HTML document (HEAD and BODY elements), and with the common HTML tags (P, A, H1, H2, etc.). If you need more background in HTML, please consult our Resource Guide for Web Developers article to find a tutorial.

Why use CSS?

The main philosophy of CSS is that the logical structure of an HTML document can and should be separated from its page layout and formatting. The idea is to use the HTML tags to specify only the logical structure of your document; for example, P elements are paragraphs, and H1 elements are top-level headers. Then, instead of specifying the fonts, colors, borders, and other layout and formatting parameters using HTML's now-obsolete tags and attributes (FONT, BGCOLOR, etc.), you instead use CSS, which is much more flexible and efficient.


CSS Basics

Linking HTML to CSS

You have a choice, when adding CSS to an HTML page: you can either put the CSS style information inside the HTML file, or you can put it in a separate file. I recommend you use a separate file, because it is likely that you will want to use the same style sheet for more than one page on your web site, and that's much easier (and more maintainable) if it's in a separate file. This tutorial assumes you wish to adopt the separate-file practice; if not, consult the further reading section, below.

CSS information is stored in a plain text file with default extension ".css". If the CSS file you want to use for a particular page's layout is called "mysite.css", and it is located in the same directory folder as your HTML page, then to reference it, put the following LINK element inside the HEAD element of your HTML file:

<LINK HREF="mysite.css" REL="stylesheet" TYPE="text/css" MEDIA="screen,print">

A few notes on the attributes of the LINK tag:

  • HREF: As you might guess, you can either use a relative path to the file, or a full URL (just as you can in an <A HREF> HTML tag) if the CSS file is in a different location from the HTML file.
  • MEDIA: CSS allows you to specify different layouts for different output media, such as a web browser ("screen"), a printer ("print"), and many others. My LINK example above specifies the same CSS layout for the printer and browser, and no support for other media. If you wish to separate screen and print layout, or specify other media, simply include additional LINK elements; separate the media in each LINK element by commas. Consult the further reading section, below, for more information on media.

You can also define your main styles in one file, and then add a second linked CSS file to override a few settings for one medium only (e.g. define generic styles for both screen and print, and then override a few styles for print only). The way CSS works, if you have multiple definitions, the last one takes precedence. Here's an example:

<LINK HREF="mymain.css" REL="stylesheet" TYPE="text/css" MEDIA="screen,print">
<LINK HREF="myprint.css" REL="stylesheet" TYPE="text/css" MEDIA="print">

Structure of CSS

Now that your HTML file is referencing your style sheet, you need to put style information into the "mysite.css" file (or "mymain.css" and "myprint.css"), using a text editor. Basically, a CSS file consists of a number of rules for layout, which appear sequentially in the file; if there is duplication, later rules override earlier rules. Each rule has two parts: the selector tells what HTML elements the rule corresponds to, and the declaration supplies the layout and style parameters for those elements. For instance, to specify that the H2 and H3 elements in your HTML document should have red text on a blue background, you would put the following in your CSS file:

H2,H3 {
color:red;
background-color:blue;
}

As you can see, the selector for a CSS rule is simply the HTML tag name; or you can specify more than one tag name, separated by commas. The declaration section is enclosed in curly brackets {}; each individual declaration within the section consists of a property and its value separated by a colon, and the property:value pair is followed by a semicolon. The indentation within the curly brackets is optional, but I recommend you indent your CSS rules, because it does improve readability.


Classes, Spans, and Divisions

With CSS, you have the flexibility to define different styles for H1, H2, P, HR, LI, A, and all other HTML elements, as well as a default style for the entire page (by making rules for the BODY element). Sometimes, however, you will find that even this flexibility is not enough, and therefore CSS provides Classes, Spans, and Divisions for further layout refinement.

Classes

Classes allow you to specify different layout rules for particular occurrences of a given element. For instance, maybe at the bottom of a web page you want to put a copyright notice. It might logically be a paragraph, so you would put it in a P element in HTML. However, you might want display it in smaller type than the other P tags on the page. To do this, assign the paragraph a class attribute in its P tag in the HTML document:

<P CLASS="disclaimer">Copyright (C)...</P>

Then, in the CSS file, define a rule for the "disclaimer" paragraph class, using the selector "p.disclaimer" (the tag name p, and the class name "disclaimer" that you chose, separated by a period; you can also just use ".disclaimer" as the selector):

p.disclaimer {
font-size:x-small;
}

You can choose your own names for classes; my advice is to choose ones that seem logical to you, so that in a month or a year when you are modifying your site's layout or adding a page, you won't have to spend a lot of time trying to remember why and how you did what you did.

Spans

Spans are similar to classes, except that they specify a style change for only part of an element (such as one sentence or phrase of a paragraph). For example, if you wanted to put the second sentence of a particular paragraph in italics, you could define a SPAN like this:

<P>First sentence. <SPAN CLASS="second">Second sentence</SPAN> Third sentence.</P>

In your CSS file, in this example, you would then define a rule for the selector ".second":

.second {
font-style:italic;
}

Divisions

Divisions are yet another variation -- they allow you to specify a style for a group of HTML elements as a block; typically, they are used for setting off a section of the page as a navigation bar. For instance, to create a navigation section for your site, you could define a division, using an HTML DIV tag:

<DIV CLASS="beginnav">
<H1>On This Site:</H1>
<P><A HREF=index.html>Home:</A> Read a company overview</P>
...
</DIV>

Then, in the CSS file, you could the style for this division:

.beginnav {
background-color:#ecf2e6;
...
}

I've left out some details of the HTML and CSS (... is not correct CSS syntax!) -- I'll go over these in the next section.


Layout and Formatting with CSS

Now that you have some background on the structure of CSS, you are ready to tackle the most important (in my opinion) layout and formatting options available in CSS. Each section below is intended to be self-contained, so you can choose the style elements you want to use in your web pages, and ignore the other sections.

Fonts, Colors, and Text Alignment

For each HTML element (or class, span, or division), you can specify fonts, colors, and text alignment. I especially recommend you start by choosing default page colors and fonts, by specifying styles for the BODY element (elements inherit their formatting and layout from the element that contains them, by default, and the entire page is contained in the BODY element.) Here are some CSS properties related to fonts, colors, and text alignment (examples below):

  • color: The foreground color for the element. For text elements, such as P and LI, this is the text color; for HR it is the color of the bar on the screen (but see background-color property, below!). Colors can be specified using the 16 standard color names of HTML, or using RGB notation (in CSS, RGB is specified by using a # sign, followed by 6 digits giving the color's hexadecimal RGB value, such as #ff0000 for the HTML color red, and #00ff00 for green).
  • background-color: The background color for the element; colors are specified the same way as for the color property. Note that on some browsers, to get a color HR bar, you need to specify the color using the background-color property, not the color property, so if you want to be sure your web page will render correctly, use both color and background-color properties when specifying the HR element. I will also note here that if you like background images, you can specify them using the background-image and related properties; consult the further reading section, below.
  • font-family: A list of font family names, separated by commas. When the page is rendered by a browser (or other software), the first font family in the list that the user's computer recognizes (and has installed for the medium being used) will be chosen. Since not all computers have the same fonts installed, it is a good idea to provide alternatives, and to end the list with one of the five generic font families (serif, sans-serif, cursive, fantasy, and monospace) that are universally recognized.
  • font-size: the size of font to use, which is typically specified using either an absolute size (usually in "pt" units, such as 12pt), or a size keyword (xx-small, x-small, small, medium, large, x-large, or xx-large).
  • font-style, font-variant, font-weight: The style can be set to normal, italic, or oblique; the weight to normal or bold; and the variant to normal or small-caps.
  • text-align: Possible values are left, right, center, and justify.

Here are some examples of CSS declarations using the properties above:

color: #3f3e29;
color: red;
background-color: #fff6db;
font-family: Arial, Helvetica, sans-serif;
font-family: Courier, monospace;
font-size: small;
font-size: 12pt;
font-style:italic;
font-weight:bold;
font-variant:small-caps;
text-align:center;

Link Formatting

Hyperlinks in your HTML document have special formatting properties: you can specify different styles for:

  • Un-visited links, using the a:link selector
  • Visited links, using the a:visited selector
  • When the user's mouse is hovering over the link, using the a:hover selector

Example:

a:link {
color:green;
}
a:visited {
color:maroon;
}
a:hover {
color:blue;
}

Wrapping Text Around Images

Another thing you can do with CSS is to put an image in a corner of a page, and have the page's text wrap around it. For example, you might want to put an image in the upper right corner, and have the text that is even with the image fill in the space to the image's left, and the text below the image go all the way to the right side of the page (scroll to the top of this article to see an example of what this looks like).

In CSS, this text wrapping is accomplished through style rules on the image, and the technique is called "floating" the image. Here is how you do it:

  • Assign a class, such as "floater", to the IMG tag of the image (see the section on classes, above). Put the IMG tag immediately before the text you want to wrap around it:
<IMG CLASS="floater" SRC="myimg.gif" ALT="logo">
<P>Text to wrap around this image....</P>
  • In your CSS file, use the "floater" class selector to define rules for the float property (left or right: which side the image should go on), and the margin property (to make the text stay a short distance away from actually hitting the image; margins are given as lengths, in inches, pixels, or other units). Here is an example of CSS rules that will put the image on the right side, and leave 1/4 inch of space free around the image:
.floater {
float:right;
margin:.25in;
}

Navigation Bars

Navigation bars can use CSS's block layout capabilities to specify the placement of the bar. To create a navigation bar:

  • Create divisions (see the divisions section above) for both the contents of the navigation bar, and the main content of your page. Give the navbar division a class of "navbar", and the main content division a class of "content". The two divisions should come one after the other in the BODY element of your HTML file, but the order doesn't matter (for purposes of CSS and layout anyway). An abbreviated illustration:
<BODY>

<DIV CLASS="navbar">
<P>navigation bar content goes here</P>
</DIV>

<DIV CLASS="content">
<P>main page content goes here</P>
</DIV>

</BODY>
  • For both the "navbar" and "content" divisions, specify size and position on the page (with the top, left, width, and position properties). You will also need to specify the margin, and padding properties, and will probably also want to give the two sections different background colors. "Padding" refers to the empty space left between the text and the borders of the box on the screen, and "margin" refers to the empty space between the box and its containing box. Here is an example:
.navbar {
position:absolute;
top:0;
left:0;
width:1.5in;
background-color:yellow;
padding:.1in;
margin:0in;
}
.content {
position:absolute;
top:0;
left:1.5in;
padding:.1in;
margin:.25in;
background-color:white;
}
  • Note that for print media (see section on media above), you should avoid absolute positioning (override with "static", which actually means to let the browser lay position the element in the default way), and you might also want to consider not showing the navigation bar, since it's not actually useful on the printed page (which you can do by setting its style to "display:none"). So, in the CSS file that is used for print media, you might want to override the above with:
.navbar {
display:none;
width:0;
}
.content {
position:static;
}
  • Although following these steps will create a navigation bar that looks fine and is valid HTML and CSS, there is an Internet Explorer 6.0 bug related to absolute positioning that will annoy people viewing the page: if they try to select text, Internet Explorer will select a very large portion of the page, instead of the text the user tried to highlight. Luckily, there is a work-around for this bug. Put the following JavaScript lines in your HTML HEAD element (adapted from Tom Guilder's Blog, where you can also read more about this bug):
<script type="text/javascript">
<!--
if( document.compatMode && document.compatMode == "CSS1Compat" ) {
document.onreadystatechange = function fixIE6AbsPos() {
if( !document.body ) { return; }
document.body.style.height = document.documentElement.scrollHeight + 'px';
}
}
// -->
</script>

Further Reading

The aim of this tutorial was to get you familiar with the basics of CSS; hopefully, it left you with the background and desire to learn about additional CSS features and the details I have left out. I recommend that after finishing this tutorial, you visit the W3C web site -- W3C is the standards body that maintains standards for HTML, CSS, and other Web technologies. You may also wish to consult other resources in my Resources for Web Developers article, or other articles in Poplar ProductivityWare's articles directory.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
minus one equals one
Solve this math question and enter the solution with digits. E.g. for "two plus four = ?" enter "6".