For those frustrated with the limited control over document presentation provided by straight HTML markup, Cascading Style Sheets are a welcome advance in web design. Like their counterparts in desktop publishing page-layout programs, style sheets in HTML allow authors to apply typographic styles and spacing instructions for elements on a page. The word cascading refers to what happens when several sources of style information vie for control of the elements on a page—style information is passed down from higher-level style sheets (and from parent to child element within a document) until it is overridden by a style command with more weight. (The cascading rules are discussed in detail later in this chapter.) This comes as good news for both designers who want more control over presentation, and for HTML purists who stand by the principle that style should be separate from content and structure. Style sheets make both these dreams possible.
We’ve classified style sheets as an “emerging technology” (rather than straight HTML) based on the fact that a low percentage of browsers in current use support them. Furthermore, it is difficult to develop CSS because Netscape and Internet Explorer have implemented them differently and inconsistently. As of this writing, CSS is a promising yet still somewhat risky technology.
Advantages:
- •Greater typography and page layout controls. With style sheets, you can specify traditional typography attributes such as font size, line spacing, and letter spacing. It also offers methods for specifying indents, margins, and element positioning. It even uses terminology from traditional and desktop publishing such as points and em spaces. Style is separate from structure. HTML is designed for indicating the structure of a document, to which presentation is applied by the end user’s browsing device. Over recent years, however, HTML has been extended to provide greater control over presentation (the <font> tag being the most infamous example). Style sheets, when done correctly, mark the return to the original intention of HTML by removing presentation instructions from HTML and placing them in a separate, optional area.
- Potentially smaller documents. Placing font specifications once at the beginning of the document instead of using a <font> description for every individual element can drastically cut down on the number of characters in the document, and thus its file size. As always with the Web, it is desirable to keep file sizes (and download times) as small as possible.
- Easier site maintenance. It is possible to link multiple HTML pages to a singlestyle sheet, which means you can make style changes to hundreds or thousands of web pages by editing a single file.
Disadvantages:
As of this writing, there is one major drawback to implementing style sheets: Browser support! First, style sheet information is not supported in browser versions earlier than Microsoft Internet Explorer 3.0 or Netscape Navigator 4.0. That is not as frustrating as the inconsistency of support among browsers and versions that claim they do support CSS. The World Wide Web Consortium first published its recommendation for style sheets in 1996 and they were first implemented by Internet Explorer 3.0. Since
then, as usual, Microsoft and Netscape have chosen diverging paths in the properties their browsers support and the way those properties are presented. And, of course, each browser’s support varies, making universal and browser-safe style sheet implementation a near impossibility at this time. The browser-support charts in Appendix E, CSS Compatibility, are evidence of the gap in style sheet implementations. Unfortunately, this means that style sheets cannot be relied upon for crucial display instructions for web sites with a general
audience, who are likely to still be using older browser versions. Strategies for Using Style Sheets Today
The browser-support problem is a major impediment to implementing style sheets on a wide-scale basis, especially for commercial or consumer-oriented sites. However, that does not mean that you should abandon them completely. There are ways to take advantage of style sheets today, or at least prepare for a time
when they can be relied upon completely.
- Include end tags. While current browsers don’t mind if you leave off the </p> or </li> tag, style sheets (and other advanced web technologies such as XML) do mind. It is necessary to have clearly defined text elements, including both tags. If you think you may be adding style sheet functionality to your site in the future, get ready by closing all your tags today.
- Use style sheets as “icing.” One way to create a site that degrades well to any browser is to first create a style-sheet-free site that is acceptable on all browser and platform configurations. Once you are happy with it, add style sheet information that will not affect the display in older browsers (such as <div> and <span>, and the class attribute). Choosing properties that are fully supported by the major browsers (see Appendix E) will broaden the chances your design will be seen as you intend it. For a “safe” list of CSS elements, You can improve the sophistication of the typography and other presentation for those whose browsers support styles, and still keep the site clear and fully functional for all others.
- Use browser-detection scripts. Another approach is to develop two style sheets—one that is formatted to work well in Netscape, and another customtailored for Internet Explorer. Serve up the appropriate style sheet using a simple browser-detect JavaScript.
- Use style sheets for Intranets. If you have the good fortune to be designing a site for which you know the exact browser/platform configuration for all of your users (such as a corporate Intranet or a self-contained kiosk display), feel free to use the supported style sheets to their limits.
The Future of Style Sheets
Despite a bumpy start, style sheets still hold great promise as the preferred method for specifying page presentation. In 1998, the W3C published its second style sheet proposal (CSS2), which includes additional properties and advanced methods for absolute positioning that could make tables and frames as layout devices a thing of the past. Style sheets are also a key component to programming dynamic effects
with DHTML. Ironically, both Netscape and Microsoft are promising support of CSS2 elements,
although they do not yet fully support the CSS1 specification in a bug-free manner. Hopefully, the bugs and inconsistencies will be ironed out and Version 2 and 3 browsers will fade into distant memory, taking style sheets out of the realm of the theoretical into the essential. How Style Sheets Work Rule Syntax
Style sheets consist of one or more rules for describing how a page element should be displayed. The following sample contains two rules. The first makes all the H1s in a document red; the second specifies that paragraphs should be set in 12pt. Verdana or some sans-serif font:
H1 { color: red }
P { font-size: 12pt;
font-face: Verdana, sans-serif;
}
A rule is a declaration of how a page element (whether it is a heading, a blockquote, or a paragraph) should be displayed.
The two main sections are the selector (which identifies the element to be affected) and the declaration (the style or display instructions to be applied to that element). In the sample code above, H1 and P are the selectors. The different types of selectors that may be used are discussed in the “Selectors” section of this
chapter. The declaration, enclosed in curly brackets, is made up of a property and its value. Properties are separated from their values by the colon (:) character followed by a space. A property is a stylistic parameter that can be defined, such as color, fontfamily, or line-height. A declaration may contain several property/value pairs. Multiple properties must be separated by semicolons (;). Values are dependent on the property. Some properties take measurements, some take color names, and others have a predefined list of accepted values. The syntax for measurement and color values are discussed later in this chapter. Adding Styles to an HTML Document Rules (and sets of rules) can be applied to HTML documents in three ways: as
- Inline style directions
- As a style element embedded at the top of the HTML file and
- As an external file that can be either linked to or imported into the document.
Inline styles
Style information can be added to an individual element by adding the style attribute within the HTML tag for that element. The value of the style attribute is one or more standard style declarations, as shown here:
<H1 STYLE="color: red">This Heading will be Red</H1>
<P STYLE="font-size: 12pt; font-face: Verdana, sans-serif">
This is the content of the paragraph to be set with the described styles.</P> Although a perfectly valid use of style information, inline styles are equivalent to the <font> tag in that they “pollute” the document with presentation information. Style information is still tied to each individual content element and any changes
would need to be made in every tag, in every file, rather than globally. Inline styles are best used to occasionally override higher-level rules.
Embedded style sheet
A more compact method for adding style sheets is to embed a style block in the top of the HTML document using the <style> element. The following example shows our sample rules embedded in a simple HTML document:
<HTML>
<HEAD>
<STYLE TYPE="text/css">
<!--
H1 { color: red}
P { font-size: 12pt;
font-face: Verdana, sans-serif;
}
-->
</STYLE>
<TITLE>Style Sheets</TITLE>
</HEAD>
...
</HTML>
The <style> element must be placed within the <head> tags in the document. In addition, it is usually necessary to place HTML comment tags (<!-- and -->) around the <style> contents. This hides the style information from browsers that don’t understand the <style> tag (otherwise, they could display the rules as text in the browser window). Currently, cascading style sheets are the only style sheet language, but the W3C
has prepared for the possibility of additional languages to be added in the future by providing the type attribute within the <style> element. The only viable style type as of this writing is text/css. If the type attribute is omitted, some browsers may ignore the entire style sheet.
External style sheet
The most powerful way to use styles is to collect them all in a separate text document and create links to that document from all the HTML pages in a site. In this way, you can make stylistic changes consistently across a whole site by editing the style information in a single document. This is a powerful tool for large-scale sites.
There are two ways to refer to external style sheets (which must be named with the .css suffix) from within an HTML document.
Linking
The most standard and best-supported method is to create a link to that document using the <link> tag in the <head> of the document as shown here:
<HEAD>
<LINK REL="STYLESHEET" HREF="/pathname/stylesheet.css" TYPE="text/css">
</HEAD>
The rel attribute defines the linked document’s relation to the current document— “stylesheet.” The href attribute provides the URL to the file containing the style sheet information.
The style sheet document is a simple text document that contains a collection of style sheet rules. It may not contain HTML tags, particularly the structural tags that set up an HTML document (<html>, <head>, and <body>). Importing. An alternative to linking is to import external style sheets into the <style> element using the @import function as shown: <STYLE> @import url(http://pathname/stylesheet.css);
</STYLE> @import commands must come before any style rules. The advantage to importing is that multiple style sheets can be applied to the same document (only one stylesheet can be “linked” to a document). When additional @import functions are added within the <style> element, the style information from the last file read (the one at the bottom of the list) will take precedence over the previous ones. The major drawback to @import is limited browser support.
Inheritance
An important feature of style sheets is the concept of inheritance, in which style properties are passed down from an element (the parent) to any element contained within it (the child). An element is said to inherit properties applied to elements higher in the HTML hierarchy. For instance, any style applied to a list will be inherited by every list item (<li>) within that list. If you specify that all the text in the <body> of a document should be red, all text elements contained in the body of the document will be red (unless specified otherwise).
Styles applied to specific elements will override settings higher in the hierarchy. With planning, inheritance can be used to make style specification more efficient. For example, if you’d like all the text on the page to be blue except for list items, you can set the color property at the <body> level to apply to the whole document
and then use another rule to make <li>s another color. The more specific rules override more general rules.
If two rules of equal weight are listed in a style sheet, whichever one is later in the style sheet will apply.
Conflicting Style Sheets: The Cascade
Style sheets are said to be cascading because more than one type of style sheet (inline, embedded, or external) can simultaneously affect the presentation of a single document. For example, it is possible to add inline styles to a document that is already linked to an external style sheet.
With several styles applied to a document, conflicts are certain to arise. For example, when an inline style says the paragraph should be maroon, but the external style sheet says all paragraphs are blue, which style gets used?
The W3C anticipated this situation and devised a hierarchical system that assigns different weights to each type of style information. This cascade order provides aset of rules for resolving conflicts between different style sheets. Styles with more weight (those defined at the more specific level) will take precedence over styles set in a higher-level style sheet.
As in inheritance, more specific rules override more general rules. This allows you to design a general style for a whole site, then modify it for particular pages or elements, alleviating redundancy.
The following list shows the hierarchy of style instructions from general to specific, such that elements lower in the list have more weight and will override styles above them.
- Browser default settings
- User style settings (set in browser)
- Linked external style sheet
- Imported style sheets; when multiple styles are imported, the commands fromthe last file read will take precedence over the first ones listed
- Embedded style sheets (rules within the <style> element); later rules have greater weight than earlier rules
- Inline style information
- HTML tag attributes, which override all style information defined anywhere
Selectors
Selectors are the parts of the rule that identify the element (or elements) to which the style will be applied. There are several methods for identifying elements.
Type Selector
The simplest type of selector calls an HTML element by its tag, as shown:
H1 { color: blue }
H2 { color: blue }
P { color: blue }
Type selectors can be grouped into comma-separated lists so a single property willapply to all of them. The following code has the same effect as the previous code:
H1, H2, P { color: blue }
<div> and <span>
Two HTML elements, div and span, were especially created for use with style sheets. They have no inherent properties of their own, but can be used to designateelements on a web page that should be affected by style sheet instructions. They will be ignored by browsers that do not understand them.
The <div> tag is used to delimit block-level tags and can contain other HTML
elements within it.
<DIV STYLE="color: blue">
<H1>Headline!</H1>
<P>This is a whole paragraph of text.</P>
</DIV>
The <span> tag is used inline to change the style of a set of characters:
<P>This is a paragraph and <SPAN STYLE="color: blue">this area will be treated differently</SPAN> from the rest of the paragraph</P> When used with the CLASS and ID attribute selectors, these tags can be used to create custom-named elements, sort of like creating your own HTML tags.
Deleted and inserted text
Deleted text (<del>) and inserted text (<ins>) are two new logical elements introduced by the HTML 4.0 Specification. They have no inherent style information and rely on style sheets (not the browser) for text display instructions. They are used when it is important to track edits to a document, such as in legal
contracts. For instance, deleted text might be hidden from view or displayed in strikethrough text. Inserted text might be displayed in bold or in a different color from the original document.
DEL { text-decoration: line-through }
INS { color: red }
Contextual Selectors
You can also specify style attributes for HTML elements based on the context in which they appear.
As we’ve seen already, a simple selector specifies that all emphasized text within a document should be red.
EM { color: red }
Using a contextual selector (written as a list of simple selectors separated by white space) you can specify that only the emphasized text that appears within a list item will be green:
LI EM { color: green }
In other words, this affects emphasized text when it appears in the context of a list item element. If both of these rules for emphasized text were to appear in the same document, the contextual selector (because it is more specific) would take precedence over the simple selector. Several contextual selectors can be grouped together in comma-separated lists.
The following code makes bold (<B>) text red when it appears in the context of a
heading:
H1 B, H2 B, H3 B { color: red }