Полезная информация


Special Edition Using HTML 4

Previous chapterNext chapterContents


- 17 -
Applying Cascading Style Sheets

by Jerry Honeycutt

Understanding Style Sheets

A critical portion of W3C's HTML 4.0 recommendation is style sheets, particularly if you're interested in dynamic HTML. Style sheets let you separate the content of your HTML documents from their presentation. And by associating scripts with HTML elements, you can change the document's format as the user interacts with the it.

The two major Web browsers, Internet Explorer 4.0 and Netscape Communicator, support style sheets defined by HTML 4.0: Cascading Style Sheets Level 1 (CSS1). They both support CSS1 to varying degrees, though.

W3C treats the style sheet mechanism (the HTML used to associate styles with a document) separately from the style sheet language (the statements that specify formatting). CSS1 is the most prevalent style sheet language, however, so I'll show you how to write CSS1 rules in this chapter in addition to how to associate style sheets with an HTML document. Appendix B, "Style Sheet Property Reference," covers CSS1 in more depth.

Attaching a Style Sheet to Your HTML Document

HTML 4.0 provides the mechanism to associate a style sheet with a document, but it doesn't care what style sheet language you're using--CSS1 or even a more complex language that's yet to be invented. Regardless, you must specify the style sheet language to the browser so that it knows how to parse it. You do so by using the <META> tag:

<META http-equiv="Content-Style-Type" content="text/css">

You can also define the style sheet language using the following HTTP header:

Content-Style-Type: text/css

If you don't specify a style sheet language using the <META> tag or an HTTP header, the default is CSS1. Even though the default is CSS1, make a point of explicitly defining the language you're using so that you don't rely on this default behavior.

Linking a Style Sheet

You can create a style sheet in a separate file and then apply that style sheet to all the pages on your Web site. I recommend this method because it makes creating a consistent Web site much easier. In fact, you can create a corporate style sheet and have all members of your organization use it with their Web sites.

You store a linked style sheet in a text file with the CSS file extension. It's a plain text file that you can create with your favorite text editor (Notepad, for example). The format of the text file is readable and easy to understand. Thus, you won't have any trouble creating your style sheets by hand.

To link to a style sheet stored in a separate file, store all your styles in the CSS file and link your HTML files to it using the <LINK> tag, like this:

<LINK REL=STYLESHEET HREF="http://www.myserver.com/mysheet.css" TYPE="text/css">

Assign the URL of the style sheet to the HREF attribute. Set TYPE to the MIME type of the style sheet language, "text/css" for CSS1.


TIP: Store your corporate style sheets in a common location on the Web server and then have everyone who is creating Web pages reference that style sheet from his or her HTML files. Everyone can even use the same <LINK> tag. In this way, you can have a more consistent look across all the Web pages on the server.

Embedding a Style Sheet

You don't have to store your style sheet in a separate file. You can embed the style sheet inside each HTML file. Note that the styles within an embedded style sheet only affect the HTML within that file; thus, you can't embed a style sheet in an HTML file and expect to use that across multiple HTML files without copying it into each file.

You use the <STYLE> container to embed a style sheet in your HTML file. Put this container between the <HTML> and <BODY> tags of your file, like this:

<HTML>
<HEAD>
</HEAD>
<STYLE TYPE="text/css">
  Style definitions go here
</STYLE>
<BODY>
</BODY>
</HTML>

The <STYLE> tag's most important attribute, called TYPE, specifies the MIME type. It identifies the style sheet language so that browsers that don't support style sheets or the specified language won't display the contents of the <STYLE> container. For CSS1, set it to "text/css". The <STYLE> tag has three other attributes that you learn about later in this chapter: MEDIA, LANG, and DIR.

Defining Styles Inline

Inline styles are simple styles that you define on-the-fly. You can use inline styles to quickly change the appearance of a single tag, for example. You can also use inline styles to override a style for a particular tag. For example, if you've defined a style that sets the color of the <H1> tag to blue, you can set the color of a specific element using the <H1> tag to red.

With inline styles, you define a tag's style within the tag itself. You do this by using the STYLE attribute, which is supported by all the child tags of the BODY tag. To define an inline style, add the STYLE attribute to the tag for which you want to change the style and set its value to the string representing the style definition, like this:

<H1 STYLE="color: blue">


NOTE: If an inline style conflicts with an embedded or linked style, the inline style wins. If in a linked style sheet you define the color of an <H1> tag to be blue and you also define the color of a particular <H1> tag within your HTML file to be red, the browser will display that particular occurrence of the <H1> tag using the color red.

You can use inline styles with the <DIV> tag to set the style for an entire block of HTML within your document. This works because of the concept of inheritance, which you learn about later in this chapter. For example, if you want to change the text color of an entire block of tags to blue, you can put those tags in the <DIV> container and define a style for the <DIV> tag that sets the text color to blue. It looks like this:

<DIV STYLE="color: blue">
  <H1>This is a heading</H1>
   <P>This is a paragraph. It will look blue in the user's browser</P>
</DIV>

You can also use inline style sheets with the <SPAN> tag to change the formatting for a few words or even just a few letters. For example:

This is a <SPAN STYLE="color: blue">simple</SPAN> block of text.


CAUTION: Don't abuse inline styles. They'll quickly clutter your HTML file so that it's more difficult to read and much more difficult to maintain. This obviously diminishes the greatest advantage of style sheets: separating format from content.

Importing Style Sheets

You learned about linking to a style sheet earlier in this chapter. You can also use the @import keyword to import a style sheet into your HTML file; however, many browsers don't support @import yet. Remember that you're just importing the text file, thus you have to insert it in the <STYLE> container. In this manner, importing a style sheet works just like embedding a style sheet into your HTML file. For example:

<STYLE TYPE="text/css">
@import url(http://www.myserver.com/style.css);
</STYLE>


Matters of Style
Style sheets can help you create a great-looking site. Other style matters, however, contribute as greatly, if not more, to the impact your site has on its users:


Naming and Combining Style Sheets

The <LINK> tag's TITLE attribute allows you to name the style sheet. If you don't assign a value to TITLE, the style sheet is persistent, and the user can't disable it (unless he disables style sheets altogether). Assigning a value to TITLE changes the style sheet to default, and the user can choose from any number of named style sheets.

The browser combines any style sheets with the same title that have the alternate keyword attached to the REL attribute. In the following example, the browser applies the styles in both FIRST.CSS and SECOND.CSS because both <LINK> tags assign alternate to REL and have the same title.

<LINK TYPE="text/css" REL="alternate stylesheet" TITLE="Example" HREF=first.css>
<LINK TYPE="text/css" REL="alternate stylesheet" TITLE="Example" HREF=second.css>


Understanding the Cascade
You can use multiple styles to control how your Web page looks; the browser follows a certain set of rules to determine the precedence and resolves conflicts between styles (cascading order). For example, you can define a style sheet for your Web site, and the reader can have her own style sheet. The cascading rules determine who wins if both style sheets define a style for a particular type of text.
Each rule is assigned a weight by the browser. When the browser is working with the occurrence of a particular tag, it finds all the rules that apply to it. The browser then sorts those rules by their weight, applying the style with the greatest weight. In general, there are just a few rules that you need to be aware of when dealing with competing style sheets:

You can also override the precedence for a rule by using the important keyword. In the following example, the assignment of red to the property color and the assignment of sans-serif to the property font-family are marked as important. Thus, the browser will not override these styles. If two competing style sheets mark the same property as important, however, the rules in the previous list apply.

H1 {color: red ! important font-weight: bold font-family: sans-serif ! important}


Creating Style Sheets for Each Type of Media

HTML 4.0 style sheets give you the opportunity to specify the type of media for which a style sheet is intended. The browser uses the style sheet that's associated with the media on which the user is viewing the document. For example, you can associate three style sheets with an HTML document. The browser uses the first one if a user views the document on the screen, the second one for printing, and the third one for speech.

To associate a style sheet with a media type, you use the <STYLE> tag's MEDIA attribute. In the following example, you see two different style sheets. The browser uses the first one for the screen and the second for printing.

<STYLE TYPE="text/css" media="screen">
  style definitions
</STYLE>
<STYLE TYPE="text/css" media="print">
  style definitions
</STYLE>

Table 17.1 describes the media types that HTML 4.0 supports.

Table 17.1  HTML 4.0 Media Types

Type Description
Screen Style sheet intended for a computer screen
Print Style sheet intended for a printer
Projection Style sheet intended for overheads
Braille Style sheet intended for Braille devices
Speech Style sheet intended for speech synthesizer
All Style sheet intended for all devices

Adding Rules to a Style Sheet

Linked and embedded style sheets allow you to define styles for one or more individual tags. For example, you can create a style sheet that defines styles for the <H1>, <H2>, <P>, and <EM> tags. Each style definition is called a rule. A rule contains a selector (the HTML tag), followed by the declaration (the definition of the style). The rule's selector ties the style's definition to tags you use in the HTML file. The following is an example of what a rule that defines a style for each occurrence of the <H1> tag looks like:

H1 {color: blue}

The declaration is enclosed in curly braces ({}). Each item in the declaration has two parts: the property name and the value you're assigning to the property, separated by a colon (:). In the previous example, color is the property name, and blue is the value you're assigning to it. HTML predefines dozens of property names (font-size, font-style, color, margin-right, and so on), which you'll learn about in Appendix B. Each property also accepts a predefined type and range of values.

The following example shows you a few rules contained within an embedded style sheet:

<STYLE TYPE="text/css">
  H1 {color: blue}
  P {font-size: 10pt}
</STYLE>

Setting Multiple Properties in a Single Rule

You can set multiple properties within a single declaration. You do this by separating each assignment with a semicolon (;):

H1 {color: blue; font-size: 12pt; text-line: center}

In this example, the browser displays each occurrence of the <H1> tag using the color blue, font size of 12 points, and centered in the browser window. For all other properties, the browser uses its default values. For example, it sets the font-style property to normal.

Grouping Selectors Together in a Single Rule

If you want to define a similar style for several tags, you can list them individually in your style sheet, like this:

P {font-size: 12pt}
UL {font-size: 12pt}
LI {font-size: 12pt}

You can group the selectors together, however, and define a rule for them as a group. The following example groups the selectors in the previous example on one line and defines a rule that sets the font-size property to 12pt:

P, UL, LI {font-size: 12pt}

Note the comma between each selector in the list. Omitting this comma means a totally different thing (see the following section, "Defining Parent-Child Relationships in Rules," later in this chapter).

Defining Parent-Child Relationships in Rules

With HTML style sheets, you can be very specific about when a style is applied to a tag. For example, you may want to define two styles for the <LI> tag: one that's applied when it's a child of the <UL> tag and another when it's a child of the <OL> tag. You do this with contextual selectors.

Contextual selectors define the exact sequence of tags for which a style will be applied. In other words, you can specify that a style applies to a particular tag, such as <LI> only if it's a child of the <OL> tag, like this:

OL LI {list-style-type: decimal}

You can also specify that a particular style applies to the <LI> tag only if it's a child of the <UL> tag, like this:

UL LI {list-style-type: square}

Note the list of selectors is not comma separated. Separating each selector with a comma would cause all the tags in the list to be assigned the rule.


Understanding Inheritance
In HTML, tags inherit certain properties from their parents. For example, all the tags within the <BODY> tag (<P> and <UL>) inherit certain properties from the <BODY> tag. Likewise, the <LI> tag inherits properties from the <UL> tag that contains it.
Consider the following bit of HTML:
<STYLE TYPE="text/css">
P {color: blue}
</STYLE>
<BODY>
<P>Hello. This is a paragraph of text. <EM>This text is emphasized</EM> </P>
</BODY>

The style sheet for this example sets the color for the <P> tag to blue. There is no definition for the <EM> tag. You might expect the text in the <EM> tag to change back to the default color: black. That's not the case. Because the <EM> is within the container tag <P> (it's a child, in other words), the <EM> tag inherits the color property from the <P> tag.


Working with Classes in Your Style Sheets

A class defines a variation of style, which you refer to in a specific occurrence of a tag using the CLASS attribute. For example, you can define three variations of the H1 style and then use each one in the appropriate context. You define a class much like you normally define a style, only you add an arbitrary class name to the end of the tag, separating them with a period, as in the following example:

H1.blue {color: blue}
H1.red {color: red}
H1.black {color: black}

Then, when adding the <H1> tag to your HTML document, you set the CLASS attribute to indicate exactly which style you're using:

<H1 CLASS=red>Red Heading</H1>


TIP: You can address all the tags within a particular class by omitting the tag name from the selector, like this: .red {color: red}. After defining this style, any tag that you associate with the red class, will be displayed using the color red.

Defining a Style for a Specific Element

You can use an inline style to define how a particular element looks by assigning the style to the element's STYLE attribute. You can make your HTML document easier to read, however, by giving an element an ID; then you associate a style with that element using its ID.

For example, the following <P> tag assigns test to the ID attribute:

<P ID=test>This is a test paragraph</P>

You can define a rule that affects only that element by using the its ID as the selector for the rule, prefixed with a pound sign (#), like this:

#test {color: red}

Working with Special Elements such as Anchors

CSS defines a concept called pseudo-classes, which are special selectors that define how certain HTML elements look at certain times. For example, CSS defines a pseudo-class that defines how an anchor looks when the user clicks on it or how the first line of a paragraph looks. In general, pseudo-classes look like the following example.

selector:pseudo-class { property: value }

CSS1 defines three pseudo-classes for anchors: link, active, and visited. When you use these pseudo-classes with the A selector in a style rule, you're defining how a normal, active, and already visited link looks on the Web page. For instance, the following example defines unvisited links as blue, active links as red, and visited links as yellow:

A:link {color: blue}
A:active {color: red}
A:visited {color: yellow}

CSS1 defines a pseudo-class for the first line of a paragraph. Any style rule you assign to the selector called first-line applies to the first line of that element. If you use the first-line pseudo-class with the <P> tag, for example, the first line of each paragraph uses the formatting you specified in the rule. The following example causes the first line of every paragraph to be bold:

P:first-line {font-weight: bold}

Similarly, you can change the formatting for the first letter in an element using the first-letter pseudo-class. This is handy to create special effects such as drop-caps:

P:first-letter {font-size: 400%; float: left}

Adding Comments to Your Style Sheet

If your style sheet gets complicated or you need to explain why you've made a particular design decision, you can add a comment to the style sheet. Comments only serve to document your style sheet; they don't have any impact on how the browser displays the HTML document.

Enclose your comments between /* and */. The following example shows you what a one-line comment looks like:

BODY {margin-left: 1in}          /* Create space for sliders */
H1 {font-size: 16; margin-left: -1in}     /* Out one inch */
H2 {font-size: 14; margin-left: -1in}     /* Out one inch */

You can also use the /* and */ characters to create block comments. This is useful to explain an entire portion of your style sheet. Like this:

/*----------------------------------------------------------------
  The margin-left property is set to one inch for the BODY tag.
  Since all of its enclosed tags will inherit this setting, the
  entire page will appear to be indented by one inch. The first-
  and second-level headings are indented to the left by one inch
  so that they slide out into the margin.
  --------------------------------------------------------------*/
BODY {margin-left: 1in}          /* Create space for sliders */
H1 {font-size: 16; margin-left: -1in}     /* Out one inch */
H2 {font-size: 14; margin-left: -1in}     /* Out one inch */

Hiding Style Sheets from Older Browsers

HTML style sheets are new. Internet Explorer and Netscape are the first browsers to support them. You need to worry about all those browsers that don't support style sheets, however.

Most browsers are designed to simply ignore the tags and attributes they don't understand. Thus, they'll ignore the <STYLE> tag, for example. They won't necessarily ignore what you put in the <STYLE> tag, though, and will display its contents as text on the Web page. To get around this problem, you can use an HTML comment within the <STYLE> tag to hide the style definitions, like this:

<STYLE TYPE="text/css">
<!--
H1 {color: red}
-->
</STYLE>

Browsers that don't support style sheets display the HTML files with their default styles. They'll ignore the style definitions.


TIP: Open each HTML document in browsers that don't support style sheets so that you can verify how your Web pages look.

Building Style Sheets Using a Program

Building a style sheet by hand is easy; building a large style sheet by hand is tedious and error prone. Recently, several programs have been introduced to make building style sheets rather simple:

FIG. 17.1
Sheet Stylist's user interface is intuitive, with most work being done via this tabbed dialog box.

Aside from style sheet editors, many of the popular HTML editors you learn about in Chapter 42, "Using HTML and Site Tools," support CSS1. For example, HotDog and HotMetaL both support CSS1.


TIP: To see style sheets in action, visit Microsoft's Web site at http://www.microsoft.com, and view the home page's source.


Previous chapterNext chapterContents


© Copyright, Macmillan Computer Publishing. All rights reserved.