Cascading Style Sheets: Chapter 2
Cascading Style Sheets
Designing for the Web
by Håkon Wium Lie and Bert Bos
(Publisher's Note: This information is from the manuscript that is still being copyedited. The technical merit of this work is accurate, but please note there may still be notes throughout that will be removed in the final book.)
CHAPTER 2: Enter CSS
As we explained in Chapter 1, "The Web and HTML," HTML elements enable a Web page designer to mark up a document as to its structure. The HTML specification lists some guidelines on how browsers should display these elements. For example, you can be reasonably sure that the contents of a STRONG element will displayed bold. Also, you can pretty much trust that most browsers will display the content of an H1 element using a big font size -- at least bigger than the P element and bigger than the H2 element. But beyond trust and hope, you don't have any control over how your text appears.
CSS changes that. CSS puts you, the designer, in the driver's seat. We devote much of the rest of this book to explaining what you can do with CSS. In this chapter, we begin by introducing you to the basics of how to write CSS and how CSS and HTML work together to affect both the structure and appearance of your document.
Rules and Style Sheets
CSS is based on rules and style sheets. A rule is statement about one stylistic aspect of one or more elements. A style sheet is one or more rules that apply to an HTML document.
An example of a simple style sheet is a sheet that consists of one rule. In the following example, we add a color to all first-level headings (H1). Here's the line of code-the rule-that we add:
H1 { color: red }
Let's take a closer look at the anatomy of a rule.
Anatomy of a Rule
A rule consists of two parts:
- Selector - the part before the left curly brace
- Declaration - the part within the curly braces
H1 { color: red } __ ______________ | | Selector Declaration
The selector is the link between the HTML document and the style. It specifies what element(s) is to be affected by the declaration. The declaration is that part of the rule that sets forth what the effect will be. In the previous example, the selector is H1 and the declaration is "color:red." Hence, all H1 elements will be affected by the declaration, that is, they will be shown in red.
The above selector is based on the type; of the element: it selects all element of type 'H1'. This kind of selector is called type selector. Any HTML element type can be used as a type selector. (It doesn't make sense to use invisible (see table 1.1) element types as selectors though.) Type selectors are the simplest kind of selectors and the only one we will use in this chapter. We discuss other kinds of selectors in the next chapter, "Selectors."
Anatomy of a Declaration
A declaration has two parts separated by a colon:
- Property - the part before the colon
- Value - the part after the colon
H1 { color: red } _____ ___ | | Property Value
The property is a quality or characteristic that something possesses. In the previous example, it is "color." (the 'color' property is discussed in Chapter 7, "Color.") CSS11 defines more than 50 properties and we can assign values to all of them.
CSS1 refers to Cascading Style Sheets level 1, the specification for CSS. Currently CSS1 is the only specification in what we expect will be a family of CSS specifications. You can read more about these efforts in Chapter 15, "Looking Ahead." For now, we use CSS1 when we refer specifically to the first-level specification and CSS in statements that apply to forthcoming specifications as well.
The value is a precise specification of the property. In the example, it is "red," but it could just as easily be blue, green, yellow, or some other color.
Figure 2.1 shows the diagram of a rule using as an example the H1 element whose contents we turned red. The curly braces ({ }) and colon (:) make it possible for the browser to distinguish between the selector, property, and value.
Selector | Property | | Value _| _|___ _|_ H1 { color: red } __________ | Declaration
Figure 2.1 Diagram of a rule
Grouping Selectors and Rules
In designing CSS, brevity was a goal. We figured that if we could reduce the size of style sheets, we could speed up the development of style sheets that were written "by hand," that is, without an authoring tool (a computer program that helps you author HTML documents). Also, short style sheets load faster than longer ones. CSS therefore includes several mechanisms to shorten style sheets by way of grouping selectors and declarations.
For example, consider these three rules:
H1 { font-weight: bold } H2 { font-weight: bold } H3 { font-weight: bold }
All three rules have exactly the same declaration -- they set the font to be bolder. (This is done using the 'font-weight' property, which we discuss in Chapter 4, "Fonts.") Since all three declarations are identical, we can group the selectors into a comma-separated list and only list the declaration once, like this:
H1, H2, H3 { font-style: bold }
This rule will produce the same result as the first three will.
A selector may have more than one declaration. For example, we could write a style sheet with these two rules:
H1 {color: red } H1 ( text-align: center }
In this case, we set all H1s to be red and to be centered on the canvas. (This is done using the Text-align property, discussed in Chapter 4, "Fonts.")
But we can achieve the same effect faster by grouping the declarations that relate to the same selector into a semicolon-separated list, like this:
H1 { color: red; text-align: center }
All declarations must be contained within the pair of curly braces. A semicolon separates the declarations and may -- but doesn't have to -- also appear at the end of the last declaration. Also, to make your code easier to read, we suggest you place each declaration on its own line, as we did here. (Browsers won't care. They'll just ignore all the extra whitespace and line breaks.)
Now you have the basics of how to create CSS rules and style sheets. However, you're not done yet. You can't simply write the style sheet, stick it wherever you want in the document, and expect it to work. It won't. You have more work to do. Next, you have to "glue" your style sheet to your HTML document.
Gluing Style Sheets to the Document
For any style sheet to affect the HTML document, it must be "glued" together. That is, the style sheet and the HTML document must be combined so that they can work together to produce the whole document. This can be done in any of four ways:
- Apply the basic, document-wide style sheet for the document by using the STYLE element.
- Apply a style sheet to an individual element using the STYLE attribute.
- Link an external style sheet to the document using the LINK element. This method is used to reference alternative style sheets that the browser can select if a previous one cannot be displayed.
- Import a style sheet using the CSS @import notation. This method is used to automatically import and merge an external style sheet with the current style sheet.
In the next section, we discuss the first method: using the STYLE element. We discuss using the STYLE attribute in Chapter 3, "Selectors," and using the LINK element and the "@import" notation in Chapter 10, "Site Style."
Gluing by Using the STYLE Element
You can glue the style sheet and HTML document together by putting the style sheet inside a STYLE element at the top of your document. The STYLE element was introduced in HTML specifically to allow style sheets to be inserted inside HTML documents. Here's a style sheet (shown in bold) glued to a sample document by using the STYLE element. The result is shown in Figure 2.2.
<HTML> <TITLE>Bach's home page</TITLE> <STYLE> H1 { color: red } </STYLE> <BODY> <H1>Bach's home page</H1> <P>Johann Sebastian Bach was a prolific composer. Among his works are: <UL> <LI>the Goldberg Variations <LI>the Brandenburg Concertos <LI>the Christmas Oratorio </UL> <H1>Historical perspective</H1> <P>Bach composed in what has been referred to as the Baroque period. </BODY> </HTML>
Figure 2.2: Adding to a style sheet a rule to turn H1s red and then gluing the style sheet to the document using the STYLE element
Notice that the STYLE element is placed after the TITLE element and before the BODY element. The title of a document does not show up on the canvas, so it is not affected by CSS styles.
The content of a STYLE element is a style sheet. However, whereas the content of such elements as H1, P, and UL appears on the canvas, the content of a STYLE element does not show on the canvas. Rather, it is the effect of the content of the STYLE element-the style sheet-that appears on the canvas. So you don't see "{ color: red }" displayed on your screen; you see instead two H1s colored red. No rules have been added that affect any of the other elements, so those elements appear in the browser's default color.
Browsers and CSS
For CSS to work as described in this book, you must use a CSS-enhanced browser, that is, a browser that supports CSS. A CSS-enhanced browser will recognize the STYLE element as a container for [alternatively: an element that contains] a style sheet and present the document accordingly. At the time of this writing, the most widely available CSS-enhanced browser is Microsoft's Internet Explorer 3.0 (MSIE3), but when you read this, more and newer browsers should support CSS1. See Appendix B for a list of the software that currently supports CSS1 and check the book's web site (https://www.awl.com/css) for an updated list. Note that throughout this book when we display examples of CSS usage, those examples appear as they would on a CSS-enhanced browser.
Some browsers, such as Netscape's Navigator (version 2.x and 3.x) don't support style sheets but they know enough about the STYLE element to fully ignore it. Next to supporting style sheets, this is the preferred behavior.
However, other browsers that do not know the STYLE element, such as Navigator 1.x and MSIE2, will ignore the STYLE tags but display content of the STYLE element. Thus, the user will end up with the style sheet printed on the top of the canvas:
At the time of writing, roughly 10% of the Web users will experience this problem. To avoid this, you can put your style sheet inside an HTML comment, which we discussed in Chapter 1. Because comments don't display on the screen, by placing your style sheet inside an HTML comment, you prevent the oldest browsers from displaying the STYLE element's content. CSS-enhanced browsers are aware of this trick, and will treat the content of the STYLE element as a style sheet.
Recall that HTML comments start with '<!--' and end with '-->'. Here's an excerpt from the previous code example that shows how you write a style sheet in an HTML comment. The comment encloses the STYLE element content only:
<HTML> <TITLE>Bach's home page</TITLE> <STYLE> <!-- H1 { color: red } --> </STYLE> <BODY> .. </BODY> </HTML>
CSS also has its own set of comments that you can use within the style sheet. A CSS comment begins with '/*' and ends with '*/'. (Those of you familiar with the C programming language will recognize these.) CSS rules put inside a CSS comment will not have any effect on the presentation of the document.
The browser also needs to be told that you are working with CSS styles sheets. Currently, CSS is the only style sheet language on the web, but this could change. Just as there is more than one image format (GIF, JPEG and PNG comes to mind), there could be more than one style sheet language. So the browser needs to be told which style sheet language is being used. This is done via the TYPE attribute of the STYLE element. The value of TYPE indicates which style sheet is being used; for CSS, that value is "text/css". Following is an excerpt from our previous sample document that shows you how you would write this:
<HTML> <TITLE>Bach's home page</TITLE> <STYLE TYPE="text/css"> <!-- H1 { color: red } --> </STYLE> <BODY> .. </BODY> </HTML>
When the browser loads a document, it checks to see if it understands the style sheet language. If it does, it will try to read the style sheet, otherwise it will ignore it. The TYPE attribute (see chapter 1 for a discussion on HTML attributes) on the STYLE element is a way to let the browser know which style sheet language is being used. We don't know for sure if it will be necessary to declare that you are using CSS, but ncluding a TYPE attribute will never hurt.
To make examples easier to read, we have chosen not to wrap style sheets in HTML comments, but we do use the TYPE attribute throughout this book.
Tree structures and inheritance
Recall from Chapter 1 the discussion about HTML representing a document with a tree-like structure and how elements in HTML have children and parents. There are many reasons for having tree-structured documents. For style sheets, there is one very good reason: inheritance. Just like children inherit from their parents, so do HTML elements. Instead of inheriting genes and money, HTML elements inherit stylistic properties.
Let's start by taking a look at the sample document:
<HTML> <TITLE>Bach's home page</TITLE> <BODY> <H1>Bach's home page</H1> <P>Johann Sebastian Bach was a <STRONG>prolific</STRONG> composer. Among his works are: <UL> <LI>the Goldberg Variations <LI>the Brandenburg Concertos <LI>the Christmas Oratorio </UL> </BODY> </HTML>
The tree structure of this document is:
HTML / \ TITLE BODY / | \ H1 P UL
Through inheritance, CSS property values set on one element will be transferred down the tree to its descendants. For example, our examples have up to now set the color to be red for elements like H1 and P. Now, say, would like to set the same color on all elements in your document. You could do this by making one rule for each element type:
<STYLE TYPE="text/css"> H1 { color: red } P { color: red } LI { color: red } </STYLE>
However, most HTML documents are more complex than our sample document, and your style sheet would soon get long. You could have shortened it by grouping selectors, but there is an even better -- and shorter -- way. Instead of setting the style on each element type, we set it on their common ancestors, the BODY element:
<STYLE TYPE="text/css"> BODY { color: red } </STYLE>
Since other elements inherit properties from the BODY element, they will all inherit the color red:
As you have seen above, inheritance is a transport vehicle that will distribute stylistic properties to descendants of an element. Since the BODY element is a common ancestor for all visible elements, 'BODY' is a convenient selector.
Overriding Inheritance
In the previous example, all elements were given the same color through inheritance. Sometimes, however, children don't look like their parents. Not surprisingly, CSS also accounts for this. Say you would like for H1 elements to be blue while the rest should be red. This is easily expressed in CSS:
<STYLE TYPE="text/css"> BODY { color: red } H1 { color: blue } </STYLE>
Since H1 is a child element of BODY (an thereby inherits from BODY), the two rules in the above style sheet are conflicting. The first one sets the color of the BODY element -- and thereby also the color of H1 through inheritance -- while the second one sets the color specifically on the H1 element. Which rule will win? Let's find out:
The reason why the second rule wins is that it is more specific</I> than the first. The first rule is very general -- it affects all elements on the canvas. The second rule only affects H1 elements and is therefore more specific.
If CSS had been a programming language, the order in which the rules were specified would determine which of them would win. CSS is not a programming language, and in the above example, the order is irrelevant. The result is exactly the same if we use this style sheet:
<STYLE TYPE="text/css"> H1 { color: blue } BODY { color: red } </STYLE>
CSS has been designed to resolve conflicts between style sheet rules like the one above. The exact rules for how to do this are quite complicated, but is described in detail in chapter 10 (Cascading and Inheritance).
Properties that don't inherit
As a general rule, properties in CSS inherit from parent to child elements as described in the previous examples. Some properties, however, don't inherit and there is always a reason why. We will use the 'background' property as an example of a property that doesn't inherit.
Let's say you want to set a background image for a page -- this is a common effect on the Web. In CSS, you can write:
<HTML> <TITLE>Bach's home page</TITLE> <STYLE TYPE="text/css"> BODY { background: url(texture.gif) blue } </STYLE> <BODY> <H1>Bach's <EM>home</EM> page</H1> <P>Johann Sebastian Bach was a prolific composer. </BODY> </HTML>
The 'background' property has a URL ("texture.gif") that points to a background image as value. (Also, a color is specified for use when the image is not available.) When the image is ready, the canvas looks like:
As you can see, the background image covers the surface like a wallpaper -- also the backgrounds of the H1 and P element have been covered. This is not du to inheritance, but to the fact that unless otherwise set, all backgrounds are transparent. So, since we haven't set the backgrounds of the H1 or P element to something else, the parent element, BODY, will shine through.
Visually, the effect of transparency is similar to inheritance: it looks like all elements have the same backgrounds. So if they are so similar, why don't we just use inheritance? There are two reasons: first, transparent backgrounds are faster to display (there is nothing to display!) than other backgrounds. [howcome: the second point may be too much on this?] Second, since background images are aligned relative to the element they belong to, you wupld otherwise not always end up with a smooth background surface.
We've given you some simple examples to get you started on understanding and using inheritance with CSS. We talk a lot more about inheritance in subsequent chapters, particularly when we discuss the various CSS properties that can be set on text and images. Chapter 10 is devoted to a more in-depth discussion of inheritance. In that chapter, called "Cascading and Inheritance," we also discuss the concept of cascading, which we introduce you to next in this chapter.
Introduction to Cascading
A fundamental feature of CSS is that more than one style sheet can influence the presentation of a document. This feature is known as cascading because the different style sheets are thought of as coming in a series. Cascading is a fundamental feature of CSS since we realized that any single document could end up with style sheets from multiple sources: the browser, the designer, and possibly the user.
Each browser will have a default style sheet that describes how it displays a document that doesn't have its own style sheet. The default style sheet contains all the presentation style rules that Web designers have come to expect; for example, the EM element is italicized. This style sheet is merged with any other style sheets the author or user has associated with the document. Since the default style sheet includes the common presentation rules, authors and users don't need to put them into their style sheets.
We have known for years that designers want to develop their own style sheets. However, we discovered that users, too, want the option of influencing the presentation of their documents. With CSS, they can do this by supplying a personal style sheet that will be merged with the browser's and the designer's style sheets. Any conflicts between the various style sheets are resolved by the browser. Usually, the designer's style sheet will have the strongest claim on the document, followed by the user's, and then the browser's default.
We go into details about cascading in Chapter 11, "Cascading and Inheritance". Before that, there is much to learn about fonts, space and colors.
Håkon Wium Lie and Bert Bos: CASCADING STYLE SHEETS: DESIGNING FOR THE WEB, (Chapter 2 and Table of Contents). © 1997 Håkon Wium Lie and Bert Bos. Reproduced by permission of the authors and Addison-Wesley Longman, Inc. All Rights Reserved. No further copying of this material is allowed without the prior written permission of the authors.
Comments are welcome
Created: Mar. 17, 1997
Revised: May 20, 1997
URL: https://webreference.com/content/css/chap2.html