Building Web pages with HTML is like painting a portrait with a paint roller. Only truly determined and tenacious souls can achieve the exact result they wanted. It's just not the right tool for precision and flexibility.
Anyone who's used HTML for more than a week knows it isn't a very effective tool for making Web pages. That's why we sometimes resort to making large GIFs when we want just the right font or layout. That's why we're forced into using convoluted table tags and invisible spacer GIFs to push things around on a page.
It's ridiculous, really. Our code gets too complicated, our GIFs too numerous, and our final pages too bandwidth-heavy. Not exactly optimal Web page construction.
But in late 1996, and quietly, stylesheets entered the scene. Officially called "cascading stylesheets" (or CSS), this was an elegant cousin to HTML that promised:Despite lukewarm support by many of our favorite Web browsers, CSS is starting to make good on these promises. It's transforming the way we make Web pages, and it's the cornerstone of the most promising Web novelty we're seeing right now: Dynamic HTML.
- More precise control than ever before over layout, fonts, colors, backgrounds, and other typographical effects.
- A way to update the appearance and formatting of an unlimited number of pages by changing just one document.
- Compatibility across browsers and platforms.
- Less code, smaller pages, and faster downloads.
This and the next four parts will be taking a tour through the land of stylesheets. You'll learn the basics of how to create and use cascading stylesheets within your Web pages, as well as the details of what you can do with fonts, typography, colors, backgrounds, and positioning. In this [part 1], we take a quick trip through the basics of stylesheets - everything you have to know to get started quickly. Let's begin by asking the most important question:What Can Cascading Stylesheets Do for Me Today?
So what's so special about stylesheets? In a nutshell, they let you do the following:Let's look at each one...
- You can separate form and structure.
- You can control layout like never before.
- You can make smaller, faster pages.
- You can maintain or update many pages at once, faster and easier than before.
- You can be browser-friendly.
You can separate form and structure.
HTML was never meant to control the form or appearance of Web pages. It's a language that defines the structure and function of elements on a page. It lets the Web browser decide how those elements should actually appear.
But we perfectionist Web designers wanted more. So we rejoiced when Netscape invented new HTML tags that let us begin to control appearance. To make body text look the way we wanted, we surrounded the <P> with <FONT FACE>, <I>, and so on. And then we put everything inside a nested table and used invisible spacer GIFs to push it over 20 pixels to create a margin. What a mess. Our code became convoluted, and it became harder and harder to create or move content to the Web quickly.
Cascading stylesheets enable us to get more control the right way: by separating the part that defines structure from the part that defines form. The HTML remains clean and simple, as originally intended. The CSS code is separated and controls appearances from afar.
You can control layout like never before.
Sure, <FONT SIZE> enables us to resize text and table tags help us create margins. But overall, what we can do with HTML is very limiting. We can't create text exactly 80 pixels tall, we can't specify margins easily, we can't control the space between lines or words, we can't precisely position images on the screen.
Until now. Stylesheets make all these things possible, and more. And the promise of what's to come is even more exciting. In the next four days, you'll see what I mean.
You can make smaller, faster pages.
Here's more good news: Stylesheets is simple text, just like HTML. No graphics, no executable program, no plug-ins, no streaming, no delays. It's as fast as straight HTML code.
And with CSS, you can do things that you previously had to resort to GIFs for. But wait, there's more! As I mentioned earlier, cascading stylesheets also mean fewer table tags and other HTML hacks cluttering up your code. Less code and fewer graphics translate into smaller file sizes.
You can maintain or update many pages faster and easier.
Without stylesheets, if I want to update the font used for body text across my entire site, I have to manually edit each page. Even if my site is served from a database, I still have to update all the templates, and within each template, every single instance of good ol' <FONT FACE>.
The whole point of stylesheets is to separate form and structure. With stylesheets, I can have all the pages on my site point to a single CSS document. If I want to change the body text, all I do is change one line in this stylesheets document, and the entire site instantly changes.
You can be browser-friendly.
Unlike some other Web technologies I could name, stylesheets code degrades gracefully. That is, users don't get a glaring broken icon if they're missing a plug-in, or code gibberish if they're using an older browser.Browsers that recognize cascading stylesheets use it. Browsers that don't ignore it.
Convinced that stylesheets are a good idea? Okay, then let's create one.
Your First Stylesheet
It's about time we get to the good stuff!
Launch your favorite HTML editor and create a basic Web page:<HTML>
<HEAD>
<TITLE>My First Stylesheet</TITLE>
</HEAD>
<BODY>
<H1>Stylesheets: The Tool of the Web Design Gods</H1>
<P>Amaze your friends! Squash your enemies!</P>
</BODY>
</HTML>
Very fancy. Now let's add some stylesheets. Simply insert the following code anywhere between the initial <HTML> and <BODY> tags:
<STYLE TYPE="text/css">
<!--
H1 { color: green; font-size: 37px; font-family: impact }
P { text-indent: 1cm; background: yellow; font-family: courier }
-->
</STYLE>
Open the page in your browser, and here's what you'll see:
Stylesheets: The Tool of the Web Design Gods
Amaze your friends! Squash your enemies!
Congratulations! You just created your first stylesheets-enhanced Web page.
(If the "Amaze your friends!" line doesn't have yellow behind it, then you'll need to update your browser, or you won't be able to complete this tutorial. Netscape Communicator or Internet Explorer 4 is recommended.)
Some Terminology
Let's look at what's going on in this newfangled code:
At the core of cascading stylesheets are rules. The simplest kind of rule looks like this:
H1 { color: green }
This rule tells the Web browser that all text surrounded by <H1></H1> should be displayed in green.
Each rule consists of a selector and a declaration. In the example above, H1 is the selector. It's the HTML tag that the style is being attached to. The declaration defines what the style actually is, and it also consists of two parts, the property (in this case, color) and the value (green).
Any HTML tag can be used as a selector. Thus, you can attach stylesheet information to any kind of element, from normal <P> text to <CODE> and <TABLE> content. You can even use some cascading stylesheet properties on graphics by applying them to <IMG>.
And as you can see from our first stylesheets example, you can also group stylesheets rules. Earlier, we set three different declarations all at once for <P>.
Similarly, you can group selectors:
H1, P, BLOCKQUOTE { font-family: arial }
This rule specifies that all text within <H1>, <P>, and <BLOCKQUOTE> tags will display in the Arial font.
Inheritance
Stylesheets rules are inherited from "parent" to "child." Let's look at an example:
B { color: blue }
This rule tells the browser that all text within <B> should be blue. But what does the browser do in the following situation?<B>All my Web pages will use cascading stylesheets within <I>four</I> weeks.</B>
There's no rule set for the <I> tag. But since here it occurs within the <B>, it inherits the latter's declarations. So, the child displays in blue, just like its parent:All my Web pages will use cascading stylesheets within four weeks.
OK, now we know how basic stylesheets rules work. And we've also seen one way to add stylesheets to Web pages. But there are also other ways. Let's take a look.Adding Styles to Web Pages
We've already seen one way to add stylesheets to Web pages. But there are actually four methods you can use, each with its own benefits:Embedding a Stylesheet
- Embed a stylesheet within the HTML document.
- Link to an external stylesheet from the HTML document.
- Import an external stylesheet into the HTML document.
- Add styles inline in the HTML document.
This is the method we used on the previous page. All the stylesheets information lives at the top of the HTML document, separated from the <BODY> of the HTML code. Here's a refresher of what the code looks like:<HTML>
When stylesheets rules are embedded, browsers honor them for the length of the HTML page. When you want to add stylesheets one page at a time, this is the way to go.
<STYLE TYPE="text/css">
<!--
H1 { color: green; font-family: impact }
P { background: yellow; font-family: courier }
-->
</STYLE>
<HEAD>
<TITLE>My First Stylesheet</TITLE>
</HEAD>
<BODY>
<H1>Stylesheets: The Tool of the Web Design Gods</H1>
<P>Amaze your friends! Squash your enemies!</P>
</BODY>
</HTML>
You probably noticed two curiosities in this code: the TYPE="text/css" attribute and the comment tags. TYPE="text/css" specifies the MIME type, so that browsers that don't support CSS can ignore stylesheet code altogether. Use it.
The comment tags (<!-- and -->) are even more important. Some older Web browsers (such as IE 2.0 for Mac) won't recognize stylesheets code in spite of the TYPE="text/css" attribute, and will display the stylesheets code itself! Not a good thing. Use comments, and this will never happen.
Linking to a StylesheetHere's where stylesheets start to get powerful. Instead of embedding stylesheets code one page at a time, you can point multiple HTML documents to one central stylesheets document. This external stylesheets file will set the rules for all of your Web pages. If you change a detail such as the font size in the stylesheets file, all of your pages will instantly reflect that change. If you maintain a large site, this is heaven.
Here's how it works: Create your Web page normally, but instead of the <STYLE> tag, you'll use the <LINK> tag within the <HEAD>, like so:<HTML>
(With a linked stylesheet, you don't have to use comment tags.)
<HEAD>
<TITLE>My First Stylesheet</TITLE>
<LINK REL=stylesheet HREF="mystyles.css" TYPE="text/css">
</HEAD>
<BODY>
<H1>Stylesheets: The Tool of the Web Design Gods</H1>
<P>Amaze your friends! Squash your enemies!</P>
</BODY>
</HTML>Now create a separate text file, called mystyles.css (you can name it anything you want). All it contains is this:
H1 { color: green; font-family: impact }
Upload this CSS file to your server the same way you would an HTML file. When you view the page in your favorite browser, you'll see that the browser has followed the <LINK> tag and honored all of its stylesheets rules in the HTML page. You can link to the same stylesheets file from an unlimited number of HTML documents, and you can use relative or absolute URLs with the HREF attribute.
P { background: yellow; font-family: courier }
Importing a Stylesheet
Importing an external stylesheet works similarly to linking. The difference is that you can't combine the linking method with other methods, whereas you can combine importing with other methods. Let's look at an example:<HTML>
Let's say that the company.css file looks like this:
<STYLE TYPE="text/css">
<!--
@import url(company.css);
H1 { color: orange; font-family: impact }
-->
</STYLE>
<HEAD>
<TITLE>My First Stylesheet</TITLE>
</HEAD>
<BODY>
<H1>Stylesheets: The Tool of the Web Design Gods</H1>
<P>Amaze your friends! Squash your enemies!</P>
</BODY>
</HTML>H1 { color: green; font-family: times }
In this example, the browser first imports the company.css rules (the @import line must always be first), then adds the embedded rules to it to get a collection of rules for the entire page.
P { background: yellow; font-family: courier }
Notice, however, that H1 has a rule both in the external stylesheets file and in the embedded styles. What does the browser do in the face of this conflict? The embedded rules win out, and the text displays as orange Impact:
Stylesheets: The Tool of the Web Design Gods
Amaze your friends! Squash your enemies!
The flexibility of importing stylesheets is wondrous. You can import as many stylesheets files as you want, and override them with embedded styles as desired.Unfortunately, Web browsers have been slower to support this method of adding stylesheets to Web pages. Only IE 4 supports importing.
Adding Styles Inline
Finally, you can also add styles inline, which means inserting stylesheets rules right in the middle of all your HTML. It might look like this:<HTML>
In this scenario, you wouldn't need any stylesheets code at all at the top of your HTML document. The inline STYLE attribute would give the browser all the information it needs.
<HEAD>
<TITLE>My First Stylesheet</TITLE>
</HEAD>
<BODY>
<H1 STYLE="color: orange; font-family: impact">Stylesheets: The Tool of the Web Design Gods</H1>
<P STYLE="background: yellow; font-family: courier">Amaze your friends! Squash your enemies!</P>
</BODY>
</HTML>
The big downside here is that you have to add the inline style code every single time you want to use it. The next <H1> text after this one would revert back to the default browser display unless you add another STYLE attribute.
Inline styles are considerably less powerful than embedded, linked, and imported styles, but you might find some use for them.
Remember, you can use more than one of these methods at a time. In fact, the power of stylesheets is in combining the ways that styles are added to pages.There are a few more tricks to cover while we're talking about the syntax of stylesheets.
Classes and Other Tricks
We've covered all the basics of the syntax of using cascading stylesheets. Now for a few more tricks and shortcuts that you'll be glad to know about.
Classes
We said before that any HTML tag can serve as a selector and have stylesheets declarations attached to it. But what if you want something more complex than that? What if, for example, you want body text to be green for the first paragraph, purple for the second paragraph, and gray for the third?
That's where classes come in. You can create three different classes of P, each one with a different stylesheet declaration. The rules (either embedded or in an external stylesheets file) would look like this:P.first { color: green }
And your HTML code would look like this:
P.second { color: purple }
P.third { color: gray }<P CLASS=first>The first paragraph, with a class name of "first."</P>
You can name classes anything you want, but make sure to use a period before the class name in the stylesheets rule.
<P CLASS=second>The second paragraph, with a class name of "second."</P>
<P CLASS=third>The third paragraph, with a class name of "third."</P>
You can also create classes that aren't attached to any HTML tag at all:.first { color: green }
This approach is more flexible, because now we can use CLASS=first with any HTML tag in the <BODY> of the page, and the text will be displayed in green.
Contextual Selectors
Let's say you want all bold text to be red, but only if that bold text occurs in regular body text. Not possible, right? Wrong. With stylesheets, even your wildest dreams can come true. Contextual selectors are selectors that demand a certain situation be true in order for their declarations to be carried out.P B { color: red }
The stylesheets rule tells the browser to make all bold text red only if it appears within <P> text. Thus, when the above HTML code is displayed by the browser, the bold text in the first line isn't red, but the bold text in the second line is.<H1><B>Emma Thompson</B>, Actress</H1>
<P>Dramatic actor, inspired comedienne. Is there <B>nothing</B> she can't do?</P>Comments
Even with the clean code that is created with stylesheets, commenting your work is a good idea. Fortunately, comments are possible within stylesheets code, and can be used on any line, like so:
P.first { color: green } /* green for the first paragraph of every page */
Cascading
H1 { text-indent: 10px; font-family: verdana }
IMG { margin-top: 100px } /* give all images a top margin */Have you asked this question yet: "Why is it called Cascading Stylesheets"? Let's discover the answer.
The Cascade: When Stylesheets Fight It Out
The scene is set for battle: In one HTML document, let's say there are three different stylesheets rules at work, and all of them use P as selector. An imported stylesheet tells the browser to display <P> text in red. An embedded stylesheet tells the browser to use blue. And an inline stylesheet tells the browser to use yellow.What's a poor Web browser to do?
Thankfully, browsers that support stylesheets have a built-in cascading order of rules that instructs them what to do in these kinds of situations. Ultimately, some kinds of stylesheets rules are more important than others. According to the official specification of cascading stylesheets, here is the order of importance:
So, inline styles override embedded styles, which override linked styles, and so on.
- Inline styles
- Embedded styles
- Linked styles
- Imported styles
- Default browser styles
Nice and elegant, right? Not so fast. Unfortunately, Netscape and Microsoft have been slightly less than perfect in implementing this order in their browsers. For example, both browsers give more importance to linked styles than embedded styles. For now, your best bet is sticking with one method of adding styles to Web pages, especially when you're sure that stylesheet rules will conflict.
But even if this cascading order worked perfectly, we still have a problem. What happens when multiple rules of the same kind conflict? What happens, for example, if one embedded rule declares <P> text green, and another embedded rule declares it red?
Thanks to the wise sages who wrote the stylesheets specification, there's an order for solving these conflicts, too. It's complicated, but here's an oversimplified guide to what browsers check for:
- Use the one stylesheets rule that's specifically declared.
Example:
BODY { color: green }
P { color: red }<P> text is specifically declared red by one rule, but it also inherits the green value from the <BODY> rule. (If you give <BODY> a declaration, everything on the entire page inherits it.) In this situation, the specific rule outweighs the inherited value, so red wins out.
- Use the one stylesheets rule that's inherited.
If step number one doesn't result in a winner (i.e., if there's no rule that's specifically declared, or if there are multiple rules that are specifically declared), the browser moves on to this step. The browser looks for an inherited rule and uses one if it finds one. If it finds none, or if there are multiple inherited rules, the browser moves on to step number three.- Use the stylesheets rules in the order they appear in the code.
Example:P { color: green }
P { color: red }
When all else fails, the browser resorts to using the order in which the rules appear. In the above example, <P> text would display in red, because it's the last rule given.
Note: The official cascading stylesheets specification goes into a lot more detail about this cascading order, including other concepts of importance and specificity, but since those are not supported by Netscape Communicator nor Internet Explorer, I won't bother to go into them here.
One final question: What happens when stylesheets rules collide with HTML tags? Take a look at this example:I { font-family: impact }
The stylesheets rule tells the browser to use Impact, but the familiar HTML <FONT FACE> tag demands Times. An obvious conflict.<P>I think <I><FONT FACE="Times">East of Eden</FONT></I> is Steinbeck's best novel.</P>
According to the official stylesheets specification, stylesheets should win out. Only if there are no applicable CSS rules should the browser use the HTML tag instead.
Unfortunately, the major browsers aren't built this way. Netscape Communicator and Internet Explorer 4 both treat HTML tags as more important than stylesheets rules. Sigh...
As you can see, Web browsers support cascading stylesheets less perfectly than we might wish. Let's get the bad news over with.The Bad News about browsers
I'll make this short and bittersweet: Cascading stylesheets are great, Web browsers not so much.
Internet Explorer 3.0 was the first browser to try to support stylesheets, and its attempt was valiant, particularly because at that point the official specification had yet to be solidified. As a result, IE 3 supports most of the CSS properties, albeit with some bugs.
You'd think that by the time IE 4 and Netscape Communicator came out, stylesheets support would be rock-solid in both of them. Well, no. It looks like the development teams at Microsoft and Netscape each had their own interpretations of some of the CSS properties. And they didn't support other properties at all.
The result? Using stylesheets can feel like walking in a minefield. Most things work, but some don't. And even when things seem to work fine, you'll find they appear differently, depending upon the browser.
As we visit the various properties of cascading stylesheets in the next four parts, we'll try to briefly mention which browsers support what. But for the details, you'll have to test as you go. It's essential when using stylesheets code to test your end product on multiple browsers and multiple platforms. This is the only way to avoid unpleasant surprises.
In the meantime, make yourself heard! Let Microsoft and Netscape know that solid support of cascading stylesheets is essential if standardized design control is ever to be achieved.That about wraps it up for part1. Let's review.
Review of Part 1
So far we discovered the MAGIC of stylesheets and the basics of their use.
Why use cascading stylesheets? Because they provide unsurpassed control over the layout of Web pages. They're also the most efficient way to maintain and update a large site, and they make for smaller pages that download faster.
How does CSS work? Through individual stylesheets rules that consist of a selector and a declaration. These rules can be embedded in an HTML document, linked to from an HTML document, imported to an HTML document, or added inline within an HTML document. Each method of adding CSS to Web pages has its own benefits.
What's next? In the next four parts, we'll dive into most of the individual stylesheets properties that give CSS its power. You've seen a few examples here; next, we'll explore each in more detail. Here are the links to the next parts:
Steve Mulder is a Senior Consultant at TSDesign, and author of Web Designer's Guide to Style Sheets. He wishes he could wallpaper his dining room using <BODY BACKGROUND>. Unfortunately, it would probably dither.