BUY THIS BOOK
Add to Cart

Print Book $34.99


Add to Cart

Print+PDF $45.49

Add to Cart

PDF $27.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £24.99

What is this?

Looking to Reprint or License this content?


CSS: The Missing Manual
CSS: The Missing Manual By David Sawyer McFarland
August 2006
Pages: 494

Cover | Table of Contents


Table of Contents

Chapter 1: Rethinking HTML for CSS
To get the most out of CSS, your HTML code needs to provide a solid, well-built foundation. This chapter shows you how to write better, more CSS-friendly HTML. The good news is that when you use CSS throughout your site, HTML actually becomes easier to write. You no longer need to worry about trying to turn HTML into the design maven it was never intended to be; instead, CSS offers all the graphic design touches you'll likely ever want. And your job becomes simpler since HTML pages written to work with CSS require less code, less typing, and are easier to create. They'll also download faster—a welcome bonus your site's visitors will appreciate (see Figure 1-1).
As discussed in the Introduction, HTML and its successor, XHTML, provide the foundation for every page you encounter on the World Wide Web. When you add CSS into the mix, the way you use HTML changes. Say goodbye to repurposing awkward HTML tags merely to achieve certain visual effects. Some HTML tags and attributes—like the <font> tag—you can forget completely. The following sections explain why.
Throughout this chapter, everything you read about HTML applies equally to XHTML. There are as many variants of HTML and XHTML as there are colors in the rainbow, though, and in the end you must pick a type and make sure your Web page identifies which one you're using. Otherwise, your visitors' browsers may gunk up your painfully crafted page. You'll learn how to tell CSS which flavor of HTML/ XHTML you're using later in this chapter.
Figure 1-1: CSS-driven Web design makes writing HTML easier. The two designs pictured here look similar, but the top page is styled completely with CSS, while the bottom page uses only HTML. The size of the HTML file for the top page is only 4k, while the HTML-only page is nearly 4 times that size at 14k. The HTML-only approach requires a lot more code to achieve nearly the same visual effects: 213 to 71 lines of HTML code for the CSS version.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
HTML: Past and Present
As discussed in the Introduction, HTML and its successor, XHTML, provide the foundation for every page you encounter on the World Wide Web. When you add CSS into the mix, the way you use HTML changes. Say goodbye to repurposing awkward HTML tags merely to achieve certain visual effects. Some HTML tags and attributes—like the <font> tag—you can forget completely. The following sections explain why.
Throughout this chapter, everything you read about HTML applies equally to XHTML. There are as many variants of HTML and XHTML as there are colors in the rainbow, though, and in the end you must pick a type and make sure your Web page identifies which one you're using. Otherwise, your visitors' browsers may gunk up your painfully crafted page. You'll learn how to tell CSS which flavor of HTML/ XHTML you're using later in this chapter.
Figure 1-1: CSS-driven Web design makes writing HTML easier. The two designs pictured here look similar, but the top page is styled completely with CSS, while the bottom page uses only HTML. The size of the HTML file for the top page is only 4k, while the HTML-only page is nearly 4 times that size at 14k. The HTML-only approach requires a lot more code to achieve nearly the same visual effects: 213 to 71 lines of HTML code for the CSS version.
When a bunch of scientists created the Web to help share and keep track of technical documentation, nobody called in the graphic designers. All the scientists needed HTML to do was to clearly structure information for easy comprehension. For example, the <h1> tag indicates an important headline, while the <h2> tag represents a lesser heading, usually a subheading of the <h1> tag. Another favorite, the <ol> (ordered list) tag, creates a numbered list for things like "Top 10 reasons not to play with jellyfish."
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Writing HTML for CSS
If you're new to Web design, you may need some helpful hints to guide your forays into HTML (and to steer clear of well-intentioned, but out-of-date HTML techniques). And if you've been building Web pages for a while, then you may have picked up a few bad HTML-writing habits that you're better off forgetting. The rest of this chapter introduces you to some HTML writing habits that will make your mother proud—and help you get the most out of CSS.
HTML adds meaning to text by logically dividing it and identifying the role that text plays on the page: for example, the <h1> tag's the most important introduction to a page's content. Other headers let you divide up the content into other, less important, but related sections. Just like the book you're holding, for example, a Web page should have a logical structure. Each chapter in this book has a title (think <h1>); and several sections (think <h2>), which in turn contain smaller subsections. Imagine how much harder it would be to read these pages if every word just ran together as one long paragraph.
For a good resource on HTML/ XHTML check out HTML & XHTML: The Definitive Guide (O'Reilly) by Chuck Musciano and Bill Kennedy, or visit www.w3schools.com for online HTML and XHTML tutorials. For a quick list of all available HTML and XHTML tags, visit www.w3schools.com/tags/.
HTML provides many other tags besides headers for marking up (that's the M in HTML) content to identify its role on the page. Among the most popular are the <p> tag for paragraphs of text, and the <ul> tag for creating bulleted (non-numbered) lists. Lesser-known tags can indicate very specific types of content, like <abbr> for abbreviations and <code> for computer code.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Importance of the Doctype
As discussed in the box in Section 1.2.4, HTML follows certain rules—these rules are contained in a Document Type Definition file, otherwise known as a DTD. A DTD is an XML document that explains what tags, attributes, and values are valid for a particular type of HTML. And for each version of HTML, there's a corresponding DTD. By now you may be asking, "But what's all this got to do with CSS?"
Everything, if you want your Web pages to appear correctly and consistently in Web browsers. You tell a Web browser which version of HTML or XHTML you're using by including what's called a doctype declaration at the beginning of a Web page. This doctype declaration is the first line in the HTML file and not only defines what version of HTML you're using (such as HTML 4.01 transitional) but also points to the appropriate DTD file out on the Web. When you mistype the doctype declaration, you can throw most browsers into an altered state called quirks mode.
Quirks mode is browser manufacturers' attempts to make their software behave like browsers did circa 1999 (in the Netscape 4 and Internet Explorer 5 days). If a modern browser encounters a page that's missing the correct doctype, then it thinks "Gee, this page must have been written a long time ago, in an HTML editor far, far away. I'll pretend I'm a really old browser and display the page just as one of those buggy old browsers would display it." That's why, without a correct doctype, your lovingly CSS-styled Web pages may not look as they should, according to current standards. If you unwittingly view your Web page in quirks mode when checking it in a browser, you may end up trying to fix display problems that are related to an incorrect doctype and not the incorrect use of HTML or CSS.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Creating Styles and Style Sheets
Even the most complex and beautiful Web sites, like the one in Figure 2-1, start with a single CSS style. As you add multiple styles and style sheets, you can develop fully formed Web sites that inspire designers and amaze visitors. Whether you're a CSS novice or a Style Sheet Samurai, you need to obey a few basic rules about how to create styles and style sheets. In this chapter you'll start at square one, learning the basics of creating and using styles and style sheets.
Some people learn better by doing rather than reading. If you'd like to try your hand at creating styles and style sheets first and then come back here to read up on what you just did, then turn to Section 2.5 for a hands-on tutorial.
A single style defining the look of one element on a page is a pretty basic beast. It's essentially just a rule that tells a Web browser how to format something on a Web page—turn a headline blue, draw a red border around a photo, or create a 150-pixel-wide sidebar box to hold a list of links. If a style could talk it would say something like, "Hey Browser, make this look like that." A style is, in fact, made up of two elements: The Web-page element that the browser formats (the selector) and the actual formatting instructions (the declaration block). For example, a selector can be a headline, a paragraph of text, a photo, and so on. Declaration blocks can turn that text blue, add a red border around a paragraph, position the photo in the center of the page—the possibilities are endless.
Figure 2-1: Every CSS-driven Web page starts with a single CSS style. Here, a basic style (left) sets the groundwork for the body of the entire page (right).
Technical types often follow the lead of the W3C and call CSS styles rules. This book uses the terms "style" and "rule" interchangeably.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Anatomy of a Style
A single style defining the look of one element on a page is a pretty basic beast. It's essentially just a rule that tells a Web browser how to format something on a Web page—turn a headline blue, draw a red border around a photo, or create a 150-pixel-wide sidebar box to hold a list of links. If a style could talk it would say something like, "Hey Browser, make this look like that." A style is, in fact, made up of two elements: The Web-page element that the browser formats (the selector) and the actual formatting instructions (the declaration block). For example, a selector can be a headline, a paragraph of text, a photo, and so on. Declaration blocks can turn that text blue, add a red border around a paragraph, position the photo in the center of the page—the possibilities are endless.
Figure 2-1: Every CSS-driven Web page starts with a single CSS style. Here, a basic style (left) sets the groundwork for the body of the entire page (right).
Technical types often follow the lead of the W3C and call CSS styles rules. This book uses the terms "style" and "rule" interchangeably.
Of course, CSS styles can't communicate in nice clear English like the previous paragraph. They have their own language. For example, to set a standard font color and font size for all paragraphs on a Web page, you'd write the following:
	p { color: red; font-size: 1.5em; }
This style simply says, "Make the text in all paragraphs—marked with <p> tags—red and 1.5 ems tall." (An em is a unit of measurement that's based on a browser's normal text size. More on that in Chapter 6.) As Figure 2-2 illustrates, even a simple style like this example contains several elements:
  • Selector. As described earlier, the selector tells a Web browser which element or elements on a page to style—like a headline, paragraph, image, or link. In Figure 2-2, the selector (p) refers to the <p> tag, which makes Web browsers format all <p> tags using the formatting directions in this style. With the wide range of selectors that CSS offers and a little creativity, you'll master your pages' formatting. (The next chapter covers selectors in depth.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding Style Sheets
Of course, a single style won't transform a Web page into a work of art. It may make your paragraphs red, but to infuse your Web sites with great design, you need many different styles. A collection of CSS styles comprises a style sheet. A style sheet can be one of two types— internal or external, depending on where the style information's located: in the Web page itself, or in a separate file linked to the Web page.
Most of the time, external style sheets are the way to go, since they make building Web pages easier and updating Web sites faster. They contain all your style information in a single file. With just a line of code, you attach the external style sheet to an HTML page and completely alter that page's appearance. You can revamp the look of an entire site by editing a single text file: the style sheet.
On the receiving end, external style sheets help Web pages open faster. When you use an external style sheet, your Web pages can contain only basic HTML—no byte-hogging HTML tables or <font> tags, and no internal CSS style code. Furthermore, when a Web browser downloads an external style sheet, it stores the file on your visitor's computer (in a behind-the-scenes folder called a cache) for quick access. When your visitor hops to other pages on the site that use the same external style sheet, there's no need for the browser to download the style sheet again. The browser simply pulls the external style sheet from its cache—a significant savings in download time.
When you're working on your Web site and previewing it in a browser, the cache can work against you. See the box in Section 2.5.1 for a workaround.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Internal Style Sheets
An internal style sheet is a collection of styles that's part of the Web page's code, always between opening and closing HTML <style> tags in the page's <head> portion. Here's an example:
	<style type="text/css">
	h1 {
	    color: #FF7643;
	    font-face: Arial;
	}
	p {
	    color: red;
	    font-size: 1.5em;
	}
	</style>
	</head>
	<body>

	/* The rest of your page follows…*/
You can place the <style> tag and its styles after the <title> tag in the head of the page, but Web designers usually place them right before the closing </head> tag as shown here.
The <style> tag is HTML, not CSS. But its job is to tell the Web browser that the information contained within the tags is CSS code and not HTML. Creating an internal style sheet's as simple as typing one or more styles between the <style> tags.
Internal style sheets are easy to add to a Web page, and provide an immediate visual boost to your HTML. But they aren't the most efficient method for designing an entire Web site composed of many Web pages. For one thing, you need to copy and paste the internal style sheet into each page of your site—a time consuming chore that adds bandwidth-hogging code to each page.
But internal style sheets are even more of a hassle when you want to update the look of a site. For example, say you want to change the <h1> tag, which you originally decided should appear as large, green, bold type. But now you want small, blue type using the Courier type face. Using internal style sheets, you'd need to edit every page. Who has that kind of time? Fortunately, there's a simple solution to this dilemma— external style sheets.
It's also possible (though rarely advisable) to add styling information to an individual HTML tag without using a style sheet. The tutorial in Section 2.5.1 shows you how to perform that maneuver using an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
External Style Sheets
An external style sheet is nothing more than a text file containing all your CSS rules. It never contains any HTML code—so don't include the <style> tag—and always ends with the extension .css. You can name the file whatever you like, but it pays to be descriptive. Use global.css, for example, to indicate a style sheet used by every page on the site, or use form.css to name a file containing styles used to make a Web form look good.
If you have a page with an internal style sheet, but want to use an external style sheet, then just cut all of the code between the <style> tags (without the tags themselves). Then create a new text file, and paste the CSS into the file. Save the file with a .css extension—
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tutorial: Creating Your First Styles
The rest of this chapter takes you through the basic steps for adding inline styles, writing CSS rules, and creating internal and external style sheets. As you work through this book, you'll help design a fictitious Web site called CosmoFarmer.com, creating various aspects of its design, and eventually styling entire pages of the site. To get started, you need to download the tutorial files located on the book's companion Web site at www.sawmac.com/css/. Click the tutorial link and download the Zip archive containing the files (detailed instructions for unzipping the files are on the Web site as well). Each chapter's files are in a separate folder, named chapter_2, chapter_3, and so on.
Next, you need to launch your favorite Web page editing software, whether it's a simple text editor like Notepad or TextEdit, or a visually oriented program like Dreamweaver or Microsoft Expression Web Designer (for information on selecting an editor, see Section 3.6).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Selector Basics: Identifying What to Style
Every CSS style has two basic parts: a selector and a declaration block. (And if that's news to you, go back and read the previous chapter.) The declaration block carries the formatting properties—text color, font size, and so on—but that's just the pretty stuff. The magic of CSS lies in those first few characters at the beginning of every rule—the selector. By telling CSS what you want it to format (see Figure 3-1), the selector gives you full control of your page's appearance. If you're into sweeping generalizations, then you can use a selector that applies to many elements on a page at once. But if you're a little more detail oriented (OK, a lot more), other selectors let you single out one specific item or a collection of similar items. CSS selectors give you a lot of power: This chapter shows you how to use them.
Figure 3-1: The first part of a style, the selector, indicates the element or elements of a page to format. In this case, h1 stands for "every heading 1 or <h1> tag on this page."
If you'd rather get some hands-on experience before studying the ins and outs of CSS selectors, then jump to the tutorial in Section 3.1.
Tag selectors—sometimes called type selectors—are extremely efficient styling tools, since they apply to every occurrence of an HTML tag on a Web page. With them, you can make sweeping design changes to a page with very little effort. For example, when you want to format every paragraph of text on a page using the same font, color, and size, you merely create a style using p (as in the <p> tag) as the selector. In essence, a tag selector redefines how a browser displays a particular tag.
Prior to CSS, in order to format text, you had to wrap that text in a <font> tag. To add the same look to every paragraph on a page, you often had to use the <font> tag multiple times. This process was a lot of work, and required a lot of HTML, making pages slower to download and more time-consuming to update. With tag selectors you don't actually have to do anything to the HTML—just create the CSS rule, and let the browser do the rest.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tag Selectors: Page-Wide Styling
Tag selectors—sometimes called type selectors—are extremely efficient styling tools, since they apply to every occurrence of an HTML tag on a Web page. With them, you can make sweeping design changes to a page with very little effort. For example, when you want to format every paragraph of text on a page using the same font, color, and size, you merely create a style using p (as in the <p> tag) as the selector. In essence, a tag selector redefines how a browser displays a particular tag.
Prior to CSS, in order to format text, you had to wrap that text in a <font> tag. To add the same look to every paragraph on a page, you often had to use the <font> tag multiple times. This process was a lot of work, and required a lot of HTML, making pages slower to download and more time-consuming to update. With tag selectors you don't actually have to do anything to the HTML—just create the CSS rule, and let the browser do the rest.
Tag selectors are easy to spot in a CSS rule, since they bear the exact same name as the tag they style—p, h1, table, img, and so on. For example, in Figure 3-2, the h2 selector (top) applies some font styling to all <h2> tags on a Web page (bottom).
Figure 3-2: A tag selector affects every instance of the tag on the page. This page has three <h2> tags (indicated by the black labels at the left edge of the browser window). A single CSS style with a selector of h2 controls the presentation of every <h2> tag on the page.
As Figure 3-2 makes clear, tag selectors don't get the less than (<) and greater than (>) symbols that surround HTML tags. So when you're writing a rule for the <p> tag, for example, just type the tag's name—p.
Tag selectors have their downsides, however. What if you want
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Class Selectors: Pinpoint Control
When you don't want every instance of a paragraph or heading tag to get the same styling, CSS lets you create a class selector with a name of your choosing, and then selectively apply it to certain bits of HTML on your page. For example, you can create a class style named .copyright and then apply it only to a paragraph containing copyright information, without affecting any other paragraphs.
Class selectors also let you pinpoint an exact element on a page, regardless of its tag. Say you want to format a word or two inside of a paragraph, for example. In this case, you don't want the entire <p> tag affected, just a single phrase inside it, so you can use a class selector to indicate just those words. You can even use a class selector to apply the same formatting to multiple elements that have different HTML tags. For example, you can give one paragraph and one second-level heading the same styling—perhaps a color and a font that you've selected to highlight special information, as shown in Figure 3-3. Unlike tag selectors which limit you to the existing HTML tags on the page, you can create as many class selectors as you like and put them anywhere you want.
When you want to apply a class selector to just a few words contained inside another tag (like the middle paragraph in Figure 3-3), you need a little help from the <span> tag (Section 1.2.2). See the box in Section 3.1 for more detail.
You've probably noticed the period that starts every class selector's name—such as .copyright and .special. It's one of a few rules to keep in mind when naming a class:
  • All class selector names must begin with a period. That's how Web browsers spot a class selector in the style sheet.
  • CSS permits only letters, numbers, hyphens, and underscores in class names.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
ID Selectors: Specific Page Elements
CSS reserves the ID selector for identifying a unique part of a page like a banner, navigation bar, or the main content area. Just like a class selector, you create an ID by giving it a name in CSS and then you apply it by adding the ID to your page's HTML code. So what's the difference? As explained in the box in Section 3.1, ID selectors have some specific uses in JavaScript-based or very lengthy Web pages. Otherwise, compelling reasons to use IDs over classes are few.
When deciding whether to use a class or an ID, follow these rules of thumb:
  • To use a style several times on a page, you must use classes. For example, when you have more than one photo on your page, use a class selector to apply styling—like a border—to each of them.
  • Use IDs to identify sections that occur only once per page. CSS-based layouts often rely on ID selectors to identify the unique parts of a Web page, like a sidebar or footer. Part 3 shows you how to use this technique.
  • Consider using an ID selector to sidestep style conflicts, since Web browsers give ID selectors priority over class selectors. For example, when a browser encounters two styles that apply to the same tag but specify different background colors—the ID's background color wins. (See Section 5.4.3 for more on this topic.)
Although you should apply only a single ID to a single HTML tag, a browser won't blow up or set off alarm bells if you apply the same ID to two or more tags on the same page. In fact, most browsers will apply the CSS from an ID style correctly in this case. However, your HTML won't validate (see Section 1.2.4) and your Web designer friends may stop talking to you.
Should you decide to use an ID selector, creating one is easy. Just as a period indicates the name of a class selector, a pound or hash symbol identifies an ID style. Otherwise, follow the exact same naming rules used for classes (Section 3.1). This example provides background color and sizing:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Styling Tags Within Tags
Choosing whether to style your page with tag selectors or class selectors is a tradeoff. Tag selectors are fast and easy, but they make every occurrence of a tag look the same, which is fine—if you want every <h1> on your page to look exactly like all the rest. Class and ID selectors give you the flexibility to style individual page elements independently, but creating a new CSS style just to change one heading's font takes a heck of a lot more work—and HTML code. What you need is a way to combine the ease of tag selectors with the precision of classes and IDs. CSS has just the thing— descendent selectors.
You use descendent selectors to format a whole bunch of tags in a similar manner (just like tag selectors), but only when they're in a particular part of a Web page. It's like saying, "Hey you <a> tags in the navigation bar, listen up. I've got some formatting for you. All you other <a> tags, just move along; there's nothing to see here."
Descendent selectors let you format a tag based on its relationship to other tags. To understand how it works, you need to delve a little bit more deeply into HTML. On the bright side, the concepts underlying descendent selectors help you understand several other selector types, too, as discussed later in this chapter.
Descendent selectors were called contextual selectors in CSS 1.
The HTML that forms any Web page is akin to a family tree, where the HTML tags represent various family members. The first HTML tag you use on a page—the <html> tag—is like the grandpappy of all other tags. The <html> tag surrounds the <head> tag and the <body> tag, which makes <html> the ancestor of both. Similarly, a tag inside of another tag is a descendent. The <title> tag in the following example is the <head> tag's descendent:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Styling Groups of Tags
Sometimes you need a quick way to apply the same formatting to several different elements. For example, maybe you'd like all the headers on a page to share the same color and font. Creating a separate style for each header—h1, h2, h3, h4 and so on—is way too much work, and if you later want to change the color of all of the headers, then you have six different styles to update. A better approach is to use a group selector. Group selectors let you apply a style to multiple selectors at the same time.
To work with selectors as a group, simply create a list of selectors separated by commas. So to style all of the heading tags with the same color, you can create the following rule:
	h1, h2, h3, h4, h5, h6 { color: #F1CD33; }
This example consists of only tag selectors, but you can use any valid selector (or combination of selector types) in a group selector. For example, here's a selector that applies the same font color to the <h1> tag, the <p> tag, any tag styled with the .copyright class, and the tag with the #banner ID.
	h1, p, .copyright, #banner { color: #F1CD33; }
If you want a bunch of page elements to share some but not all of the same formatting properties, then you can create a group selector with the shared formatting options, and individual rules, with unique formatting, for each individual element. The ability to use multiple styles to format a single element is a powerful CSS feature. See Chapter 5 for details.
You can think of a group selector as shorthand for applying the same style properties to several different page elements. CSS also gives you a sort of über group selector—the universal selector. An asterisk * is universal selector shorthand for selecting every single tag.
For example, say you want all the tags on your page to appear in bold type. Your group selector might look something like the following:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Pseudo-Classes and Pseudo-Elements
Sometimes you need to select parts of a Web page that don't have tags per se, but are nonetheless easy to identify, like the first line of a paragraph, or a link as you move your mouse over it. CSS gives you a handful of selectors for these doohickeys—pseudo-classes and pseudo-elements.
Four pseudo-classes let you format links in four different states based on how a visitor has interacted with that link. They identify when a link's in one of the following four states:
  • a:link selects any link that your guest hasn't visited yet, while the mouse isn't hovering over or clicking it. This style is your regular, unused Web link.
  • a:visited is a link that your visitor has clicked before, according to the Web browser's history. You can style this type of link differently than a regular link to tell your visitor, "Hey, you've been there already!"
  • a:hover lets you change the look of a link as your visitor passes the mouse over it. The rollover effects you can create aren't just for fun—they can provide useful visual feedback for buttons on a navigation bar.
    You can also use the :hover pseudo-class on elements other than links. For example, you can use it to highlight text in a <p> or <div> when your guests mouse over it.
    In Internet Explorer 6 and earlier, :hover works only on links. For a JavaScript workaround, see the box in Section 3.6.2.4.
  • a:active lets you determine how a link looks as your visitor clicks. In other words, it covers the brief nanosecond when someone's pressing the mouse button, before releasing it.
Chapter 9 shows you how to design links using these selectors to help your visitors click their way around your site.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Advanced Selectors
The CSS 2 guidelines provide a few more powerful selectors that give you even finer control over Web page styling. Like some of the selectors you've seen previously, the selectors in this section don't work in Windows Internet Explorer 6 and earlier. (But you can try the JavaScript workaround in the box in Section 3.6.2.4.)
Similar to the descendent selectors described earlier in this chapter, CSS lets you format the children of another tag with a child selector. The child selector uses an additional symbol—an angle bracket (>) to indicate the relationship between the two elements. For example, the selector body > h1 selects any <h1> tag that's a child of the <body> tag.
Unlike a descendent selector, which applies to all descendents of a tag (children, grandchildren, and so on), the child selector lets you specify which child of which parent you mean. For example, in Figure 3-6, there are two <h2> tags. Using a plain old descendent selector—body h2—selects both <h2> tags. Even though both <h2> tags are inside of the <body> tag, though, only the second one is a child of the <body> tag. The first <h2> is directly inside of a <div> tag, so its parent is <div>. Since the two <h2> tags have different parents, you can use a child selector to get at them individually. To select only the second <h2> tag, your child selector looks like this: body > h2. If you want the first <h2> tag, then you must use this child selector instead: div > h2.
Figure 3-6: The diagram (right) shows the relationship between HTML tags (left).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tutorial: Selector Sampler
In the rest of this chapter, you'll create a variety of selector types and see how each affects a Web page. This tutorial starts with the basic selector types and then moves on to more advanced styles.
To get started, you need to download the tutorial files located on this book's companion Web site at www.sawmac.com/css/. Click the tutorial link and download the files. All of the files are enclosed in a ZIP archive, so you'll need to unzip them first. (Detailed instructions for unzipping the files are on the Web site.) The files for this tutorial are contained inside the folder named chapter_03.
  1. Open selector_basics.html in your favorite text editor
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Saving Time with Inheritance
Children inherit traits from their parents—eye color, height, male-pattern baldness, and so on. Sometimes, we inherit traits from more distant ancestors like grandparents or great-grandparents. As you saw in the previous chapter, the metaphor of family-relations is part of the structure of HTML as well. And just like humans, HTML tags can inherit CSS properties from their ancestors.
In a nutshell, inheritance is the process by which CSS properties applied to one tag are passed on to nested tags. For example, a <p> tag is always nested inside of the <body> tag, so properties applied to the <body> tag get inherited by the <p> tag. Say you created a CSS tag style (Section 3.1) for the <body> tag that sets the color property to a dark red. Tags that are descendents of the <body> tag—that is, the ones inside the <body> tag—will inherit that color property. That means that any text in those tags—<h1>, <h2>, <p>, whatever—will appear in that same dark red color.
Inheritance works through multiple generations as well. If a tag like the <em> or <strong> tag appears inside of a <p> tag, then the <em> and the <strong> tags also inherit properties from any style applied to the <body> tag.
As discussed in Chapter 3, any tag inside of another tag is a descendent of that tag. So a <p> tag inside the <body> tag is a descendent of the <body>, while the <body> tag is an ancestor of the <p> tag. Descendents (think kids) inherit properties from ancestors (think parents and grandparents).
Although this sounds a bit confusing, inheritance is a really big time-saver. Imagine if no properties were passed onto nested tags and you had a paragraph that contained other tags like the <em> tag to emphasize text or the <a> tag to add a link. If you created a style that made the paragraph purple, 24px tall, using the Arial font, it would be weird if all the text inside the <em> tag reverted to its regular, "browser-boring" style (see Figure 4-1). You'd then have to create another style to format the <em> tag to match the appearance of the <p> tag. What a drag.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Is Inheritance?
In a nutshell, inheritance is the process by which CSS properties applied to one tag are passed on to nested tags. For example, a <p> tag is always nested inside of the <body> tag, so properties applied to the <body> tag get inherited by the <p> tag. Say you created a CSS tag style (Section 3.1) for the <body> tag that sets the color property to a dark red. Tags that are descendents of the <body> tag—that is, the ones inside the <body> tag—will inherit that color property. That means that any text in those tags—<h1>, <h2>, <p>, whatever—will appear in that same dark red color.
Inheritance works through multiple generations as well. If a tag like the <em> or <strong> tag appears inside of a <p> tag, then the <em> and the <strong> tags also inherit properties from any style applied to the <body> tag.
As discussed in Chapter 3, any tag inside of another tag is a descendent of that tag. So a <p> tag inside the <body> tag is a descendent of the <body>, while the <body> tag is an ancestor of the <p> tag. Descendents (think kids) inherit properties from ancestors (think parents and grandparents).
Although this sounds a bit confusing, inheritance is a really big time-saver. Imagine if no properties were passed onto nested tags and you had a paragraph that contained other tags like the <em> tag to emphasize text or the <a> tag to add a link. If you created a style that made the paragraph purple, 24px tall, using the Arial font, it would be weird if all the text inside the <em> tag reverted to its regular, "browser-boring" style (see Figure 4-1). You'd then have to create another style to format the <em> tag to match the appearance of the <p> tag. What a drag.
Inheritance doesn't just apply to tag styles. It works with any type of style; so when you apply a class style (see Section 3.1) to a tag, any tags inside that tag inherit properties from the styled tag. Same holds true for ID styles, descendent selectors, and the other types of styles discussed in Chapter 3.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How Inheritance Streamlines Style Sheets
You can use inheritance to your advantage to streamline your style sheets. Say you want all the text on a page to use the same font. Instead of creating styles for each tag, simply create a tag style for the <body> tag. (Or create a class style and apply it to the <body> tag.) In the style, specify the font you wish to use, and all of the tags on the page inherit the font: body { font-family: Arial, Helvetica, sans-serif; }. Fast and easy.
You can also use inheritance to apply style properties to a section of a page. For example, like many Web designers, you may use the <div> tag (Section 3.1) to define an area of a page like a banner, sidebar, or footer. By applying a style to a <div> tag, you can specify particular CSS properties for all of the tags inside just that section of the page. If you want all the text in a sidebar to be the same color, you'd create a style setting the color property, and then apply it to the <div>. Any <p>, <h1>, or other tags inside the <div> inherit the same font color.
You'll find lots more uses for the <div> tag when laying out a page using CSS in Part 3.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Limits of Inheritance
Inheritance isn't all-powerful. Many CSS properties don't pass down to descendent tags at all. For example, the border property (which lets you draw a box around an element) isn't inherited, and with good reason. If it were, then every tag inside an element with the border property would also have a border around it. For example, if you added a border to the <body> tag, then every bulleted list would also have a box around it, and each bulleted item in the list would also have a border (Figure 4-2).
There's a complete list of CSS properties in Appendix A, including details on which ones get inherited.
Figure 4-1: Inheritance lets tags copy properties from the tags that surround them.
Top: The paragraph tag is set with a specific font-face, size, and color. The tags inside each paragraph inherit those properties so they look like the rest of the paragraph.
Bottom: If inheritance didn't exist, the same page would look like this figure. Notice how the strong, em, and a tags inside the paragraph retain the font-face, size, and color defined by the browser. To make them look like the rest of the paragraph, you'd have to create additional styles—a big waste of time.
Figure 4-2: Fortunately, not all properties are inherited. The border applied to the paragraphs at top isn't inherited by the tags inside those paragraphs. If they were, you'd end up with an unattractive mess of boxes within boxes within boxes (bottom).
Here are examples of times when inheritance doesn't strictly apply:
  • As a general rule, properties that affect the placement of elements on the page, or the margins, background colors, and borders of elements aren't inherited.
  • Web browsers use their own inherent styles to format various tags: headings are big and bold, links are blue, and so on. When you define a font-size for the text on a page and apply it to the <body> tag, headings still appear larger than paragraphs, and <h1> tags are still larger than <h2> tags. It's the same when you apply a font color to the <body>; the links on the page still appear in good old-fashioned, Web-browser blue.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tutorial: Inheritance
In this three-part tutorial, you'll see how inheritance works. First, you'll create a simple tag selector and watch it pass its characteristics on to nested tags. Then, you'll create a class style that uses inheritance to alter the formatting of an entire page. Finally, you'll see where CSS makes some welcome exceptions to the inheritance rule.
To get started, you need to download the tutorial files located on this book's companion Web site at www.sawmac.com/css/. Click the tutorial link and download the files. All of the files are enclosed in a ZIP archive, so you'll need to unzip them first. (Detailed instructions for unzipping the files are on the Web site.) The files for this tutorial are contained in the folder named chapter_04.
To see how inheritance works, start by adding a single tag style and see how it affects the tags nested inside. The next two parts of this tutorial will build upon your work here, so save the file when you're done.
  1. Open the file inheritance.html in your favorite text editor.
    Now add an internal style sheet to this file.
    In general, it's better to use external style sheets for a Web site, for reasons discussed in Chapter 2 (Section 2.2). But sometimes it's easier to start your CSS-based design in an internal style sheet, as in this example, and turn it into an external style sheet later.
  2. Click directly after the closing </title> tag. Hit Enter (Return), and then type <style type="text/css"> .
    This opening style tag lets a Web browser know that CSS instructions are to follow.
    You need to create a style that applies to all <p> tags.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Managing Multiple Styles: The Cascade
Content preview·