Understand CSS

If you’ve been working through this book from the beginning, you’ve already used CSS and experienced the freedom it gives you in Web design. However, if you just jumped in here at Chapter 10, a brief orientation is in order. Newcomers to XHTML often find CSS intimidating when they come across it in a book such as this. It seems so much more complicated than XHTML that many readers just give CSS a curious glance before skipping forward to the next chapter. However, because you have been working with CSS almost from the first chapter of this book, you have already discovered that style sheets are not difficult. They’re just different. Now that CSS have been “demystified,” it’s time for you to learn more of its “nuts and bolts.”

HTML and the Problem of Style

HTML simply was never intended to address a document’s style or presentation. Granted, the extensions added to HTML over the past decade have enabled it to handle some style issues, but HTML provides clumsy presentation control at best. It only makes sense to use the proper tool for the job you need to do. In the case of presentation, that tool is CSS. However, there are a few other strong reasons to learn how to use CSS. They can be summarized in three words: deprecation, accessibility, and necessity.

  • Deprecation By now you have become quite familiar with the term deprecated. If you go to the W3C’s site (www.w3.org) and read the current recommendation for XHTML, you’ll discover that most presentational elements and attributes have been deprecated in favor of style sheets. When XHTML 2.0 becomes the official recommendation of the W3C, all presentational elements and attributes will be removed.

  • Accessibility CSS2 (the second official CSS recommendation) addresses much more than style. It deals with accessibility issues such as how to develop pages for aural (sound) browsers. Although CSS2 is poorly supported at present, that will change. One day you will be able to create style sheets targeted toward different types of browsers and link your pages to them, opening your Web site to a much broader audience.

  • Necessity While XHTML 1.0 and 1.1 are very similar to HTML in that the idea of a style sheet is optional, this will change with XHTML 2.0. XHTML 2.0 will be much closer to its parent language, XML. One distinction of XML is that all XML documents require style sheets. You can use either CSS or a language called XSL (the Extensible Stylesheet Language), but you will not have the option of ignoring style sheets then. Thus, you will find it helpful to learn CSS sooner rather than later. Of course, there is one more excellent reason to learn to use style sheets: They’re fun.

Understand the Idea of Style Sheets

Style sheets take their name from the idea of style sheets in publishing. A publisher—Osborne, for example—has a particular style for its publications. In addition, the publisher is not limited to a single style. It might use a general style that is reflected in all its publications, but more specific styles for certain series. For example, if you were to examine all the books in the How to Do Everything series, you would notice that even though subject matter differs among books, they all reflect the same basic style in fonts, layouts, headings, and so on. If you check out some of Osborne’s other books, you will notice a similarity in style at certain points, but each series has its own distinctive look and feel.

Cascading Style Sheets are intended to help you accomplish the same effect with your Web site. With CSS, you can plan a color scheme, set margins, create a layout, choose and modify fonts, and much more. All you have to do is save that style sheet as a separate document, link all your pages to it, and, voil , your entire Web site takes on the characteristics you specified in the style sheet.

Understand CSS Terminology

One reason CSS confuse people who have been learning HTML is that many of the terms are different. When they read about style sheets, it’s almost as if they are starting again from the ground floor. After getting used to elements, attributes, and values, it can be frustrating when the terminology shifts to selectors, properties, declarations, and rules. Actually, CSS terms need not be confusing as long as you learn to understand them in the context of HTML. Try understanding the basic CSS in the way described here.

  • Selector Think element here. At its simplest, a selector is an element’s name. For example, say you want to choose a style for the <h4> element. Then you use the h4 selector. The only difference is that you don’t place the “less than” and “greater than” signs around it, like you would if it were a tag. Instead, <h4> is simply written as h4. As you’ll discover later in this chapter, there can be more to it than this, but this is a good starting point.

  • Property Properties are essentially the same as attributes. Remember that with HTML, an attribute identifies a characteristic assigned to an element, such as width. In CSS, you have properties instead of attributes. These are also written differently. In HTML the width attribute is written with an equals sign (=) and quotation marks (" "), like this: width=" ". In CSS, the width property is written inside curly braces with a colon following it, like this: {width: }.

  • Value This one’s easy. A value is the same in HTML and CSS. It is the specific characteristic assigned to an element or a selector. For example, 100 pixels can be a value assigned to an HTML attribute: width="100" or a CSS property: {width: 100px}.

  • Declaration A declaration is a combination of at least one property and value. In other words, {width: 100px} is a declaration. You can include as many property/value combinations as you wish in a single style rule; however, keep in mind that if you have more than one property/value combination, you must separate them with semicolons (;). The semicolon tells the Web browser where one declaration ends and another begins. For example, if you want to specify purple text with a bold font for the same selector (element), you would separate the property/value combinations this way: {color:purple; font-weight: bold}.

  • Rule A rule is the complete “sentence” combining a selector and declaration (properties and values). A complete declaration is enclosed in curly braces. For example, the following statement would be called a rule: h1 {color: purple; font-size: 24pt; margin-left: .5in;}. If you break down the preceding rule, h1 is the selector (for the level-one heading element); the properties are color, font-size, and margin-left; and the values are purple, 24pt, and .5in, respectively.

There are some other terms, such as classes, pseudo-classes, pseudo-elements, descendent, ancestor, and inheritance. These will be covered later in this chapter.


You can put as many declarations in a rule as you want, as long as they are separated from one another by semicolons (;) and enclosed in curly braces ({ }). The single exception to this is with inline style sheets, in which you use quotation marks (" ") instead of curly braces to enclose the declarations.

Learn Style Sheet Types

There are three ways to implement style sheets in your HTML document: inline, embedded, and linked. The primary difference between these style sheets lies in where they are placed, how much of a document they affect, and the priority given to them by the browser.

Control a Single Element with an Inline Style Sheet

To control a single element only one time, use an inline style sheet. Inline style sheets, as their name implies, are placed “in line” in the individual elements of an HTML page and control only the specific element to which they are applied. To create an inline style sheet, you use the style=" " attribute. For example, to change the text for a single paragraph to a red, italicized font you would modify the opening <p> tag to read as follows:

    <p style="color: red; font-style: italic;">

Generally, browsers give inline styles priority over embedded or linked style sheets. This makes them good for doing “spot” styling, where you only need to modify a small portion of a page.

Control an Entire Page with an Embedded Style Sheet

To control styles on an entire page, use an embedded style sheet. Embedded style sheets are placed between the <head> tags of an HTML page and make use of the <style>element. An embedded style sheet controls the elements to which it is applied throughout the entire page, although any inline styles generally take precedence over it. To set the paragraph style for an entire page to 12-point bold, navy text with a yellow background, you would create a style rule like the following one:

      <style type="text/css">      p     {   color: navy;                font-weight: bold;                font-size: 12pt;                background-color: yellow; } </style>

When using embedded and external style sheets, you also should include the type=" " attribute with the value set to "text/css", as in the preceding example. This tells the browser what type of style sheet to expect.

Control Elements on Multiple Pages with a Linked Style Sheet

By creating a style sheet and saving it as a separate document, you can link multiple pages to it and the pages will take on the style specified in that sheet. For example, you could have saved the style in the preceding paragraph as a separate file—say, my_style.css—and then linked your pages to it using <link> element. The <link> element should be placed in between the <head> tags of each page you want linked to a style sheet and would be written as follows:

<link rel="stylesheet" type="text/css" href="my_style.css"> 

The rel=" " attribute tells the browser the relationship between the <link>element and whatever is being linked. Because it is possible to use this element to link more than just style sheets to a Web page, it is necessary to add the value “stylesheet” to the rel attribute. The href attribute is added to tell the browser where to find the style sheet. The value for this attribute would be the URL where the style sheet is located. In most cases, that will simply be the name of the file, as in the preceding example.

As you read this, perhaps you are beginning to see a potential problem with style sheets. With so many possibilities for specifying style, which one takes priority? That’s where the cascade comes in.

Understand the Cascade

Why are style sheets called cascading? Cascading refers to the order of priority in which styles are applied. Consider all the possible conflicting style rules that can be applied to one Web page: The browser might have its own style, the author can specify a style, and the readers who visit your site might have specified their own styles for browser display. On top of that, it is possible to have different styles specified in linked, embedded, and inline style sheets. In other words, on any given page you could have six or seven different styles all competing for the right to determine what an <h1> element should look like. So, which style gets the last word? The following questions give some guidelines for how a style’s precedence is determined:

  • Who wrote the rule? In most cases, the page author’s styles take priority over the reader’s styles; both have priority over the browser’s default styles.

  • What kind of style is it? An inline style generally (but not always) takes precedence over an embedded style; both take precedence over a linked style.

  • How specific is the selector? The selector with more detail takes priority over the selector with less detail.

  • Which style occurs last? Generally, the last declaration takes precedence over earlier ones in a document.

Project 16: Create and Use Style Sheets

The easiest way to see CSS in action and learn how to use it is to create a sample Web page and progressively add different style rules. By doing this, you will see how the different styles affect the overall look of your page. You will also gain a feel for how certain styles take precedence over others. To create a CSS sample page, follow these steps:

  1. Open template.htm and save it as css_sample.htm.

  2. Cut and paste several paragraphs of plain text in between the <body> tags of your HTML document. These paragraphs can be from any text document you want. The next illustration uses lorem.txt.

  3. Format your text into at least three paragraphs by using the <p> </p> element.

  4. Write three headlines and insert one before each paragraph. Enclose all your headlines in the <h1> element.

Your HTML code should resemble this:

<html>    <head>       <title>CSS Sample Page</title>     </head>     <body>          <h1>This is going to be a headline.</h1>          <p>Paste a paragraph of text here.</p>          <h1>This will be another headline.</h1>          <p>Paste another paragraph of text here.</p>          <h1>This is a headline, too</h1>          <p>Paste a third paragraph here.</p>     </body> </html>

When you view the page in your Web browser, you should see something similar to the following illustration. When you have saved your basic page, you’re ready to begin styling.

click to expand


Your ability to reproduce the results you see in this chapter depends directly on your browser’s capability to support style sheets. Although most browsers have some degree of support for CSS, for best results use the most recent version of Internet Explorer. If you want to test your browser for its style sheet support, the W3C has a great testing site. Just go to www.w3.org/Style/CSS/Test and click the various links. It will load test pages linked to external style sheets. You’ll be able to measure your own browser’s support for CSS easily with this free tool.

Apply an Inline Style Sheet

Begin styling your sample page by adding an inline style to the second headline, changing its font to Arial, size to 18pt, color to blue, and position to center. To do this, use the style attribute with the font size, color, and text align properties. The <h1> headline with an inline style sheet added should look like the following line of code:


Be sure to enclose all the declarations in a single set of quotation marks and separate them by semicolons; otherwise, your style will not display properly.

<h1 style="font-family: arial; font-size: 18pt; color: blue; text-align:center;">This will be another       headline.</h1>

With the inline style added, your page now should resemble the following illustration:

click to expand

Add an Embedded Style Sheet

To add an embedded style sheet to this document, you use the same syntax except that instead of enclosing declarations in quotation marks you use curly braces and place your style rules in between the <style>tags in the <head>portion of your page. For your sample page, try setting a page background color of yellow, a default font for the <p> element, and a default font size and color for the <h1> element. You can do this by following these steps:

  1. Insert a set of <style></style> tags in between the <head></head> tags on your page.

  2. Modify the opening <style> tag to read <style type="text/css">. Because there can be different kinds of style sheets, the type attribute tells the browser to expect text-based commands and the CSS language.

  3. To set the background color to yellow, you will need to write the following style rule for the body selector:

    body { background-color: yellow; }
  4. To set a style for the h1 selector that gives it an aqua background, with navy blue text, set at a size of 1.5 ems, add the following line:

    h1 { background-color: aqua; font-size: 1.5em; color: navy; }

    You may have noticed that this style uses “em” instead of points to set the font size. An em is equivalent to the document’s default font size and is calculated in relation to the width of the font’s capital M. Thus, a setting of 1.5 ems is equal to one-and-one-half times the size of your body text. Because ems are relative units of measurement, Web designers generally prefer them to points, which are absolute units of measurement. A similar but less popular measurement is the “ex,” which is calculated relative to the height of a font’s lowercase letter x.

  5. Now, tell the browser to display the p element as bold, italicized text by adding the following rule:

    p { font-weight: bold; font-style: italic; }

The completed header for your page should look like the following code listing:

<head>    <title>CSS Sample</title>    <style type="text/css"> body { background-color: yellow; } h1 { background-color: aqua; font-size: 1.5em; color: navy; } p { font-weight: bold; font-style: italic; }    </style> </head> 

When you save and display your page, your style changes should look like this:

click to expand

As you examine your results, you will see that your style specifications were all incorporated in the page, with one exception: The middle headline will still be blue with an 18-point Arial font. Remember that an inline style sheet overrides an embedded style sheet, so your first specification remains unchanged. You will see this even more clearly when you create and link to an external style sheet, which is covered next.

Create and Link to an External Style Sheet

There’s nothing difficult or mystical about creating an external style sheet; it’s merely a text document that contains a set of style rules. As with HTML, you can produce an external style sheet with a simple text editor. You need only to make certain that you save the document with a .css extension so the browser can identify it.

To construct a simple external style sheet, follow this procedure:

  1. Create a new file in Notepad or another text editor. Save it as a plain text file named my_styles.css.

  2. Copy in the following lines exactly as written:

    body    { margin-left: 15%;            background-color: rgb(80%,80%,80%) } h1      { background-color: black;           color: white;           font-size: 2.2em; } p.green {            color: green;           font-family: arial;            font-weight: bold;            border-style: double;           border-width: thick;            border-color: red; } p.large {            color: navy;            font-size: 1.25em;            background: yellow; }
  3. Save your style sheet and open css_sample.htm.

start sidebar
How to: Use Classes

In the preceding code, the selectors p.green and p.large are called class selectors. This is a way of modifying a standard selector, in this case “p,” and setting it apart as a separate class with its own properties. To call a class selector’s characteristics forth in a Web page, just add the class=” “ attribute to the appropriate element. For example, to apply the characteristics of p.large to a paragraph, you would write <p > Content </p>. Using classes gives you a virtually unlimited ability to specify style details for your page.

end sidebar

  1. Remove both the embedded and inline style sheets from css_sample.htm. (This is just so you can see the effects of the external style sheet without having to worry about the other styles overriding it.)

  2. Add the following line in the <head></head> portion of the page:

    <link rel="stylesheet" type="text/css" href="my_styles.css" />
  3. Now, to apply the class in your sample page, change the first <p> to read <p > and the second <p> to read <p >.


    It’s not necessary to put each declaration on a separate line, but it does make it easier to identify which styles you have assigned to the selectors and check your code for errors. As long as you have written the rules correctly and keep individual declarations together, the browser doesn’t care whether they’re on one line or several.

Your revised code should resemble the following code listing:

<html>    <head>       <title>CSS Sample Page</title>      <link rel="stylesheet" type="text/css"             href="my_styles.css" />    </head>    <body>       <h1>This is going to be a headline.</h1>       <p >Paste a paragraph of text here.</p>       <h1>This will be another headline.</h1>       <p >Paste another paragraph of text here.</p>       <h1>This will be a headline, too</h1>       <p>Paste a third paragraph here.</p>    </body> </html>

Save css_sample.htm and display it in your browser. Your page should look somewhat like the following illustration:

click to expand

After you view your page, experiment by adding the embedded and inline styles back into the document to see how it affects your ultimate result.


When editing CSS and XHTML documents simultaneously, you can save time by using Wordpad for your XHTML document and Notepad for the style sheet. Keep both programs open at the same time, along with a browser to view the document in, and you’ll have a much easier time editing your styles.

How to Do Everything with HTML & XHTML
How to Do Everything with HTML & XHTML
ISBN: 0072231297
EAN: 2147483647
Year: 2003
Pages: 126

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net