background
|
|
News
All in one Place
All of your regular news in one place.
More icon

RiscOS
Risc OS Info
All you need to know about Risc OS and more.
More icon
|
|
Up Image
Navigation
Search this Site
Enter your search terms

Site Breadcrumb - You are here
|
Mulder's Stylesheets Tutorial
Lesson 1

by Steve Mulder

Page 5 — 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:
    <P CLASS="first">The first paragraph, with a class name of "first."</P>
    <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 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 <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 <P> 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 }

    <H1><B>Emma Thompson</B>, Actress</H1>
    <P>Dramatic actor, inspired writer, down-to-earth comedienne. Is there <B>nothing</B> she can't do?</P>

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.

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 */

next page»