CSS Cascading Style Sheet: Your First Stylesheet

Your First Stylesheet

Table of Contents:

  • 1) Adding Styles
  • 2) Classes and Other Tricks
  • 3) When Style Sheet Fights It out

It\'s about time we get to the good stuff! Launch your favorite HTML editor and create a basic Web page:



    My First Stylesheet


    Stylesheets: The Tool of the Web Design Gods


    Amaze your friends! Squash your enemies!



     

Very fancy. Now let\'s add some stylesheets. Simply insert the following code anywhere within the tag:

    <br /> <!--<br /> H1 { color: green; font-size: 37px; font-family: impact }<br /> P { text-indent: 1cm; background: yellow; font-family: courier }<br /> --><br />

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, version 4 or higher, 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

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

text to and content. You can even use some cascading stylesheet properties on graphics by applying them to .

And as you can see from our first stylesheets example, you can also group rules together. Earlier, we set three different declarations all at once for

.

Similarly, you can group selectors:

    H1, P, BLOCKQUOTE { font-family: arial }

This rule specifies that all text within

,

, and

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 should be blue. But what does the browser do in the following situation?

All my Web pages will use cascading stylesheets within four weeks.

There\'s no rule set for the tag. But since here it occurs within the , 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. We\'ve also seen one way to add stylesheets to Web pages, but there are other methods. Let\'s take a look.


Adding Styles

There are actually four methods you can use to add styles to your page, each with its own benefits:

  • 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.
Embedding a Stylesheet

This is the method we used just before. All the stylesheets information lives at the top of the HTML document, separated from the of the HTML code. Here\'s a refresher of what the code looks like:



    My First Stylesheet
    <br /> <!--<br /> H1 { color: green; font-family: impact }<br /> P { background: yellow; font-family: courier }<br /> --><br />


    Stylesheets: The Tool of the Web Design Gods


    Amaze your friends! Squash your enemies!



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.

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 browsers that don\'t support CSS can ignore stylesheet code altogether. Use it.

The comment tags () 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! This is not a good thing. Use comments, and this snafu will never happen.

Linking to a Stylesheet

Here\'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 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 feature is heaven.

Here\'s how it works: Create your Web page normally but instead of the tag, use the <LINK> tag within the <HEAD>, like so: </p> <ul> <HTML><br /> <HEAD><br /> <TITLE>My First Stylesheet</TITLE><br /> <LINK REL=stylesheet HREF="mystyles.css" TYPE="text/css"><br /> </HEAD><br /> <BODY><br /> <H1>Stylesheets: The Tool of the Web Design Gods</H1><br /> <P>Amaze your friends! Squash your enemies!</P><br /> </BODY><br /> </HTML> </ul> <p>(With a linked stylesheet, you don\'t have to use comment tags.) </p> <p>Now create a separate text file called mystyles.css (you can name it anything you want). All it contains is this: </p> <ul> H1 { color: green; font-family: impact }<br /> P { background: yellow; font-family: courier } </ul> <p>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> <p><strong>Importing a Stylesheet</strong> </p> <p>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: </p> <ul> <HTML><br /> <HEAD><br /> <TITLE>My First Stylesheet</TITLE><br /> <STYLE TYPE="text/css"><br /> <!--<br /> @import url(company.css);<br /> H1 { color: orange; font-family: impact }<br /> --><br />


Stylesheets: The Tool of the Web Design Gods


Amaze your friends! Squash your enemies!



Let\'s say that the company.css file looks like this:

    H1 { color: green; font-family: times }
    P { background: yellow; font-family: courier }

In this example, the browser first imports the company.css rules (the @import line must always be first) and then adds the embedded rules to it to get a collection of rules for the entire page.

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 and 5 support importing, so I recommend avoiding it for the time being.

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:



    My First Stylesheet


    Stylesheets: The Tool of the Web Design Gods


    Amaze your friends! Squash your enemies!



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.

The big downside here is that you have to add the inline style code every single time you want to use it. The next

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. For example, if all your paragraphs are styled with a linked stylesheet but you want to override the style of one paragraph, you can use inline style to do so.

Remember, you can use more than one of these methods at a time. In fact, the power of stylesheets lies in combining the ways that styles are added to pages.

Classes and Other Tricks

We\'ve covered all the basics of CSS syntax. Now let\'s go over 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 wanted 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 could create three different classes of P, each one with a different stylesheet declaration. The rules (either embedded in the HTML document or in an external stylesheets file) would look like this:

    P.first { color: green }
    P.second { color: purple }
    P.third { color: gray }
And your HTML code would look like this:

    The first paragraph, with a class name of "first."


    The second paragraph, with a class name of "second."


    The third paragraph, with a class name of "third."

You can name classes anything you want, but make sure to use a period before the class name in the stylesheets rule.

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 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. It\'s not possible, right? Wrong. With stylesheets, even your wildest dreams can come true (OK, maybe I\'m exaggerating slightly). Contextual selectors are selectors that demand that a certain situation be true in order for their declarations to be carried out.

    P B { color: red }

    Emma Thompson, Actress


    Dramatic actor, inspired writer, down-to-earth comedienne. Is there nothing she can\'t do?

The stylesheets rule tells the browser to make all bold text red only if it appears within

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.

Comments

Even with the clean code that\'s 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 */
    H1 { text-indent: 10px; font-family: verdana }
    IMG { margin-top: 100px } /* give all images a top margin */

When Stylesheets Fight It Out


The scene is set for battle. Let\'s say there are three different stylesheets rules at work and all of them use P as the selector. An imported stylesheet tells the browser to display

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:

  1. Inline styles
  2. Embedded styles
  3. Linked styles
  4. Imported styles
  5. Default browser styles
So inline styles override embedded styles, which override linked styles, and so on.

It\'s nice and elegant, right? Not so fast. Unfortunately, Netscape and Microsoft have been slightly less than perfect in implementing this order in their browsers. If I apply styles to the same selector using all these methods, then the browsers get it right and treat inline styles as most important, embedded styles as next-most important, and so on.

But if my styles are applied to different selectors and inheritance is involved, all hell breaks loose. For example, both browsers give more importance to linked styles than embedded styles. For now, your best bet is to stick 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 would still have a problem. What happens when multiple rules of the same kind conflict? What happens, for example, if one embedded rule declares

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:

  1. Use the one stylesheets rule that\'s specifically declared.

    Example:

    BODY { color: green }
    P { color: red }

    text is specifically declared red by one rule, but it also inherits the green value from the rule. (If you give a declaration, everything on the entire page inherits it.) In this situation, the specific rule outweighs the inherited value, so red wins out.

  2. 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:

  3. 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,

    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 well supported by the major browsers, 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 }

    I think East of Eden is Steinbeck\'s best novel.

The stylesheets rule tells the browser to use Impact, but the familiar HTML tag demands Times. It\'s an obvious conflict.

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 both treat HTML tags as more important than stylesheets rules if the HTML is closer to the affected text. Sigh.

As you can see, there are all sorts of problems with the browsers\' support of stylesheets. Let\'s get the bad news over with.