JETZT ONLINE BESTELLEN
Third Edition November 2006
ISBN 978-0-596-52733-4
536 Seiten
EUR37.00
Weitere Informationen zu diesem Buch
Inhaltsverzeichnis |
Kolophon |
Rezensionen |
Inhaltsverzeichnis
- Chapter 1: CSS and Documents
- InhaltsvorschauCascading Style Sheets (CSS) are a powerful way to affect the presentation of a document or a collection of documents. Obviously, CSS is basically useless without a document of some sort, since it would have no content to present. Of course, the definition of "document" is extremely broad. For example, Mozilla and related browsers use CSS to affect the presentation of the browser chrome itself. Still, without the content of the chrome—buttons, address inputs, dialog boxes, windows, and so on—there would be no need for CSS (or any other presentational information).Back in the dimly remembered, early years of the Web (1990–1993), HTML was a fairly lean language. It was composed almost entirely of structural elements that were useful for describing things like paragraphs, hyperlinks, lists, and headings. It had nothing even remotely approaching tables, frames, or the complex markup we assume is necessary to create web pages. HTML was originally intended to be a structural markup language, used to describe the various parts of a document; very little was said about how those parts should be displayed. The language wasn't concerned with appearance—it was just a clean little markup scheme.Then came Mosaic.Suddenly, the power of the World Wide Web was obvious to almost anyone who spent more than 10 minutes playing with it. Jumping from one document to another was no more difficult than pointing the cursor at a specially colored bit of text, or even an image, and clicking the mouse. Even better, text and images could be displayed together, and all you needed to create a page was a plain-text editor. It was free, it was open, and it was cool.Web sites began to spring up everywhere. There were personal journals, university sites, corporate sites, and more. As the number of sites increased, so did the demand for new HTML elements that would each perform a specific function. Authors started demanding that they be able to make text boldfaced or italicized.At the time, HTML wasn't equipped to handle those sorts of desires. You could declare a bit of text to be emphasized, but that wasn't necessarily the same as being italicized—it could be boldfaced instead, or even normal text with a different color, depending on the user's browser and preferences. There was nothing to ensure that what the author created was what the reader would see.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- The Web's Fall from Grace
- InhaltsvorschauBack in the dimly remembered, early years of the Web (1990–1993), HTML was a fairly lean language. It was composed almost entirely of structural elements that were useful for describing things like paragraphs, hyperlinks, lists, and headings. It had nothing even remotely approaching tables, frames, or the complex markup we assume is necessary to create web pages. HTML was originally intended to be a structural markup language, used to describe the various parts of a document; very little was said about how those parts should be displayed. The language wasn't concerned with appearance—it was just a clean little markup scheme.Then came Mosaic.Suddenly, the power of the World Wide Web was obvious to almost anyone who spent more than 10 minutes playing with it. Jumping from one document to another was no more difficult than pointing the cursor at a specially colored bit of text, or even an image, and clicking the mouse. Even better, text and images could be displayed together, and all you needed to create a page was a plain-text editor. It was free, it was open, and it was cool.Web sites began to spring up everywhere. There were personal journals, university sites, corporate sites, and more. As the number of sites increased, so did the demand for new HTML elements that would each perform a specific function. Authors started demanding that they be able to make text boldfaced or italicized.At the time, HTML wasn't equipped to handle those sorts of desires. You could declare a bit of text to be emphasized, but that wasn't necessarily the same as being italicized—it could be boldfaced instead, or even normal text with a different color, depending on the user's browser and preferences. There was nothing to ensure that what the author created was what the reader would see.As a result of these pressures, markup elements like
<FONT>and<BIG>started to creep into the language. Suddenly, a structural language started to become presentational.Years later, we have inherited the problems of this haphazard process. Large parts of HTML 3.2 and HTML 4.0, for example, were devoted to presentational considerations. The ability to color and size text through theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - CSS to the Rescue
- InhaltsvorschauOf course, the problem of polluting HTML with presentational markup was not lost on the World Wide Web Consortium (W3C), which began searching for a quick solution. In 1995, the consortium started publicizing a work-in-progress called CSS. By 1996, it had become a full Recommendation, with the same weight as HTML itself. Here's why.In the first place, CSS allows for much richer document appearances than HTML ever allowed, even at the height of its presentational fervor. CSS lets you set colors on text and in the background of any element; permits the creation of borders around any element, as well as the increase or decrease of the space around them; lets you change the way text is capitalized, decorated (e.g., underlining), spaced, and even whether it is displayed at all; and allows you to accomplish many other effects.Take, for example, the first (and main) heading on a page, which is usually the title of the page itself. The proper markup is:
<h1>Leaping Above The Water</h1>
Now, suppose you want this title to be dark red, use a certain font, be italicized and underlined, and have a yellow background. To do all of that with HTML, you'd have to put theh1into a table and load it up with a ton of other elements likefontandU. With CSS, all you need is one rule:h1 {color: maroon; font: italic 2em Times, serif; text-decoration: underline; background: yellow;}That's it. As you can see, everything you did in HTML can be done in CSS. There's no need to confine yourself to only those things HTML can do, however:h1 {color: maroon; font: italic 2em Times, serif; text-decoration: underline; background: yellow url(titlebg.png) repeat-x; border: 1px solid red; margin-bottom: 0; padding: 5px;}You now have an image in the background of theh1that is only repeated horizontally, and a border around it, separated from the text by at least five pixels. You've also removed the margin (blank space) from the bottom of the element. These are feats that HTML can't even come close to matching—and that's just a taste of what CSS can do.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Elements
- InhaltsvorschauElements are the basis of document structure. In HTML, the most common elements are easily recognizable, such as
p,table,span,a, anddiv. Every single element in a document plays a part in its presentation. In CSS terms, at least as of CSS2.1, that means each element generates a box that contains the element's content.Although CSS depends on elements, not all elements are created equally. For example, images and paragraphs are not the same type of element, nor arespananddiv. In CSS, elements generally take two forms: replaced and nonreplaced. The two types are explored in detail in Chapter 7, which covers the particulars of the box model, but I'll address them briefly here.Section 1.3.1.1: Replaced elements
Replaced elements are those where the element's content is replaced by something that is not directly represented by document content. The most familiar XHTML example is theimgelement, which is replaced by an image file external to the document itself. In fact,imghas no actual content, as you can see by considering a simple example:<img src="howdy.gif" />
This markup fragment contains no actual content—only an element name and an attribute. The element presents nothing unless you point it to some external content (in this case, an image specified by thesrcattribute). Theinputelement is also replaced by a radio button, checkbox, or text input box, depending on its type. Replaced elements also generate boxes in their display.Section 1.3.1.2: Nonreplaced elements
The majority of HTML and XHTML elements are nonreplaced elements. This means that their content is presented by the user agent (generally a browser) inside a box generated by the element itself. For example,<span>hi there</span>is a nonreplaced element, and the text "hi there" will be displayed by the user agent. This is true of paragraphs, headings, table cells, lists, and almost everything else in XHTML.In addition to replaced and nonreplaced elements, CSS2.1 uses two other basic types of elements:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Bringing CSS and XHTML Together
- InhaltsvorschauI've mentioned that HTML and XHTML documents have an inherent structure, and that's a point worth repeating. In fact, that's part of the problem with web pages of old: too many of us forgot that documents are supposed to have an internal structure, which is altogether different than a visual structure. In our rush to create the coolest-looking pages on the Web, we bent, warped, and generally ignored the idea that pages should contain information with some structural meaning.That structure is an inherent part of the relationship between XHTML and CSS; without the structure, there couldn't be a relationship at all. To understand it better, let's look at an example XHTML document and break it down by pieces:
<html> <head> <title>Eric's World of Waffles</title> <link rel="stylesheet" type="text/css" href="sheet1.css" media="all" /> <style type="text/css"> @import url(sheet2.css); h1 {color: maroon;} body {background: yellow;} /* These are my styles! Yay! */ </style> </head> <body> <h1>Waffles!</h1> <p style="color: gray;">The most wonderful of all breakfast foods is the waffle—a ridged and cratered slab of home-cooked, fluffy goodness that makes every child's heart soar with joy. And they're so easy to make! Just a simple waffle-maker and some batter, and you're ready for a morning of aromatic ecstasy! </p> </body> </html>This markup is shown in Figure 1-4.
Figure 1-4: A simple documentNow, let's examine the various ways this document connects to CSS.First, consider the use of thelinktag:<link rel="stylesheet" type="text/css" href="sheet1.css" media="all" />
Thelinktag is a little-regarded but nonetheless perfectly valid tag that has been hanging around the HTML specification for years, just waiting to be put to good use. Its basic purpose is to allow HTML authors to associate other documents with the document containing thelinktag. CSS uses it to link style sheets to the document; in Figure 1-5, a style sheet called sheet1.css is linked to the document.
Figure 1-5: A representation of how external style sheets are applied to documentsEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Summary
- InhaltsvorschauWith CSS, it is possible to completely change the way elements are presented by a user agent. This can be executed at a basic level with the
displayproperty, and in a different way by associating style sheets with a document. The user will never know whether this is done via an external or embedded style sheet, or even with an inline style. The real importance of external style sheets is the way in which they allow authors to put all of a site's presentation information in one place, and point all of the documents to that place. This not only makes site updates and maintenance a breeze, but it helps to save bandwidth since all of the presentation is removed from documents.To make the most of the power of CSS, authors need to know how to associate a set of styles with the elements in a document. To fully understand how CSS can do all of this, authors need a firm grasp of the way CSS selects pieces of a document for styling, which is the subject of the next chapter.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 2: Selectors
- InhaltsvorschauOne of the primary advantages of CSS—particularly to designers—is its ability to easily apply a set of styles to all elements of the same type. Unimpressed? Consider this: by editing a single line of CSS, you can change the colors of all your headings. Don't like the blue you're using? Change that one line of code, and they can all be purple, yellow, maroon, or any other color you desire. That lets you, the designer, focus on design, rather than grunt work. The next time you're in a meeting and someone wants to see headings with a different shade of green, just edit your style and hit Reload. Voilà! The results are accomplished in seconds and there for everyone to see.Of course, CSS can't solve all your problems—you can't use it to change the color of your GIFs, for example—but it can make some global changes much easier. So let's begin with selectors and structure.As I've stated, a central feature of CSS is its ability to apply certain rules to an entire set of element types in a document. For example, let's say that you want to make the text of all
h2elements appear gray. Using old-school HTML, you'd have to do this by inserting<FONT COLOR="gray">...</FONT>tags in all yourh2elements:<h2><font color="gray">This is h2 text</font></h2>
Obviously, this is a tedious process if your document contains a lot ofh2elements. Worse, if you later decide that you want all thoseh2s to be green instead of gray, you'd have to start the manual tagging all over again.CSS allows you to create rules that are simple to change, edit, and apply to all the text elements you define (the next section will explain how these rules work). For example, simply write this rule once to make all yourh2elements gray:h2 {color: gray;}If you want to change allh2text to another color—say, silver—simply alter the rule:h2 {color: silver;}To illustrate the concept of rules in more detail, let's break down the structure.Each rule has two fundamental parts, the selector and the declaration block. The declaration block is composed of one or moreEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Basic Rules
- InhaltsvorschauAs I've stated, a central feature of CSS is its ability to apply certain rules to an entire set of element types in a document. For example, let's say that you want to make the text of all
h2elements appear gray. Using old-school HTML, you'd have to do this by inserting<FONT COLOR="gray">...</FONT>tags in all yourh2elements:<h2><font color="gray">This is h2 text</font></h2>
Obviously, this is a tedious process if your document contains a lot ofh2elements. Worse, if you later decide that you want all thoseh2s to be green instead of gray, you'd have to start the manual tagging all over again.CSS allows you to create rules that are simple to change, edit, and apply to all the text elements you define (the next section will explain how these rules work). For example, simply write this rule once to make all yourh2elements gray:h2 {color: gray;}If you want to change allh2text to another color—say, silver—simply alter the rule:h2 {color: silver;}To illustrate the concept of rules in more detail, let's break down the structure.Each rule has two fundamental parts, the selector and the declaration block. The declaration block is composed of one or more declarations, and each declaration is a pairing of a property and a value. Every style sheet is made up of a series of rules. Figure 2-1 shows the parts of a rule.
Figure 2-1: The structure of a ruleThe selector, shown on the left side of the rule, defines which piece of the document will be affected. In Figure 2-1,h1elements are selected. If the selector werep, then allp(paragraph) elements would be selected.The right side of the rule contains the declaration block, which is made up of one or more declarations. Each declaration is a combination of a CSS property and a value of that property. In Figure 2-1, the declaration block contains two declarations. The first states that this rule will cause parts of the document to have acolorofred, and the second states that part of the document will have abackgroundofyellow. So, all of theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Grouping
- InhaltsvorschauSo far, we've learned fairly simple techniques for applying a single style to a single selector. But what if you want the same style to apply to multiple elements? If that's the case, you'll want to use more than one selector or apply more than one style to an element or group of elements.Let's say you want
h2elements and paragraphs to have gray text. The easiest way to accomplish this is to use the following declaration:h2, p {color: gray;}By placing theh2andpselectors on the left side of the rule and separating them with a comma, you've defined a rule where the style on the right (color:gray;) applies to the elements referenced by both selectors. The comma tells the browser that there are two different selectors involved in the rule. Leaving out the comma would give the rule a completely different meaning, which we'll explore later in "Descendant Selectors."There are really no limits on how many selectors you can group together. For example, if you want to display a large number of elements in gray, you might use something like the following rule:body, table, th, td, h1, h2, h3, h4, p, pre, strong, em, b, i {color: gray;}Grouping allows an author to drastically compact certain types of style assignments, which makes for a shorter style sheet. The following alternatives produce exactly the same result, but it's pretty obvious which one is easier to type:h1 {color: purple;} h2 {color: purple;} h3 {color: purple;} h4 {color: purple;} h5 {color: purple;} h6 {color: purple;} h1, h2, h3, h4, h5, h6 {color: purple;}Grouping allows for some interesting choices. For example, all of the groups of rules in the following example are equivalent—each merely shows a different way of grouping both selectors and declarations:/* group 1 */ h1 {color: silver; background: white;} h2 {color: silver; background: gray;} h3 {color: white; background: gray;} h4 {color: silver; background: white;} b {color: gray; background: white;} /* group 2 */ h1, h2, h4 {color: silver;} h2, h3 {background: gray;} h1, h4, b {background: white;} h3 {color: white;} b {color: gray;} /* group 3 */ h1, h4 {color: silver; background: white;} h2 {color: silver;} h3 {color: white;} h2, h3 {background: gray;} b {color: gray; background: white;}Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Class and ID Selectors
- InhaltsvorschauSo far, we've been grouping selectors and declarations together in a variety of ways, but the selectors we've been using are still simple ones that refer only to document elements. They're fine up to a point, but there are times when you need something a little more specialized.In addition to raw document elements, there are two other types of selectors: class selectors and ID selectors, which let you assign styles in a way that is independent of document elements. These selectors can be used on their own or in conjunction with element selectors. However, they work only if you've marked up your document appropriately, so using them generally involves a little forethought and planning.For example, say you're drafting a document that discusses ways of handling plutonium. The document contains various warnings about safely dealing with such a dangerous substance. You want each warning to appear in boldface text so that it will stand out. However, you don't know which elements these warnings will be. Some warnings could be entire paragraphs, while others could be a single item within a lengthy list or a small section of text. So, you can't define a rule using simple selectors of any kind. Suppose you tried this route:
p {font-weight: bold;}All paragraphs would be bold, not just those that contain warnings. You need a way to select only the text that contains warnings, or more precisely, a way to select only those elements that are warnings. How do you do it? You apply styles to parts of the document that have been marked in a certain way, independent of the elements involved, by using class selectors.The most common way to apply styles without worrying about the elements involved is to use class selectors. Before you can use them, however, you need to modify your actual document markup so that the class selectors will work. Enter theclassattribute:<p class="warning">When handling plutonium, care must be taken to avoid the formation of a critical mass.</p> <p>With plutonium, <span class="warning">the possibility of implosion is very real, and must be avoided at all costs</span>. This can be accomplished by keeping the various masses separate.</p>
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Attribute Selectors
- InhaltsvorschauWhen it comes to both class and ID selectors, what you're really doing is selecting values of attributes. The syntax used in the previous two sections is particular to HTML, SVG, and MathML documents (as of this writing). In other markup languages, these class and ID selectors may not be available. To address this situation, CSS2 introduced attribute selectors, which can be used to select elements based on their attributes and the values of those attributes. There are four types of attribute selectors.Attribute selectors are supported by Safari, Opera, and all Gecko-based browsers, but not by Internet Explorer up through IE5/Mac and IE6/Win. IE7 fully supports all CSS2.1 attribute selectors, as well as a few CSS3 attribute selectors, which are covered in this section.If you want to select elements that have a certain attribute, regardless of that attribute's value, you can use a simple attribute selector. For example, to select all
h1elements that have aclassattribute with any value and make their text silver, write:h1[class] {color: silver;}So, given the following markup:<h1 class="hoopla">Hello</h1> <h1 class="severe">Serenity</h1> <h1 class="fancy">Fooling</h1>
you get the result shown in Figure 2-10.
Figure 2-10: Selecting elements based on their attributesThis strategy is very useful in XML documents, as XML languages tend to have element and attribute names that are very specific to their purpose. Consider an XML language that is used to describe planets of the solar system (we'll call it PlanetML). If you want to select allplanetelements with amoonsattribute and make them boldface, thus calling attention to any planet that has moons, you would write:planet[moons] {font-weight: bold;}This would cause the text of the second and third elements in the following markup fragment to be boldfaced, but not the first:<planet>Venus</planet> <planet moons="1">Earth</planet> <planet moons="2">Mars</planet>
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Using Document Structure
- InhaltsvorschauAs I've mentioned before, CSS is powerful because it uses the structure of HTML documents to determine appropriate styles and how to apply them. That's only part of the story since it implies that such determinations are the only way CSS uses document structure. Structure plays a much larger role in the way styles are applied to a document. Let's take a moment to discuss structure before moving on to more powerful forms of selection.To understand the relationship between selectors and documents, you need to once again examine how documents are structured. Consider this very simple HTML document:
<html> <head> <base href="http://www.meerkat.web/"> <title>Meerkat Central</title> </head> <body> <h1>Meerkat <em>Central</em></h1> <p> Welcome to Meerkat <em>Central</em>, the <strong>best meerkat web site on <a href="inet.html">the <em>entire</em> Internet</a></strong>!</p> <ul> <li>We offer: <ul> <li><strong>Detailed information</strong> on how to adopt a meerkat</li> <li>Tips for living with a meerkat</li> <li><em>Fun</em> things to do with a meerkat, including: <ol> <li>Playing fetch</li> <li>Digging for food</li> <li>Hide and seek</li> </ol> </li> </ul> </li> <li>...and so much more!</li> </ul> <p> Questions? <a href="mailto:suricate@meerkat.web">Contact us!</a> </p> </body> </html>Much of the power of CSS is based on the parent-child relationship of elements. HTML documents (actually, most structured documents of any kind) are based on a hierarchy of elements, which is visible in the "tree" view of the document (see Figure 2-14). In this hierarchy, each element fits somewhere into the overall structure of the document. Every element in the document is either the parent or the child of another element, and it's often both.
Figure 2-14: A document tree structureAn element is said to be the parent of another element if it appears directly above that element in the document hierarchy. For example, in Figure 2-14, the firstpelement is parent to theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Pseudo-Classes and Pseudo-Elements
- InhaltsvorschauThings get really interesting with pseudo-class selectors and pseudo-element selectors. These selectors let you assign styles to structures that don't necessarily exist in the document, or to phantom classes that are inferred by the state of certain elements, or even by the state of the document itself. In other words, the styles are applied to pieces of a document based on something other than the structure of the document, and in a way that cannot be precisely deduced simply by studying the document's markup.It may sound like I'm applying styles at random, but I'm not. Instead, I'm applying styles based on somewhat ephemeral conditions that can't be predicted in advance. However, the circumstances under which the styles will appear are, in fact, well-defined. Think of it this way: during a sporting event, whenever the home team scores, the crowd will cheer. You don't know exactly when during a game the team will score, but when it does, the crowd will cheer, just as predicted. The fact that you can't predict the moment of the cause doesn't make the effect any less expected.Let's begin by examining pseudo-class selectors since they're better supported by browsers and are therefore more widely used.Consider the anchor element (
a), which, in HTML and XHTML, establishes a link from one document to another. Anchors are always anchors, of course, but some anchors refer to pages that have already been visited, while others refer to pages that have yet to be visited. You can't tell the difference by simply looking at the HTML markup, because in the markup, all anchors look the same. The only way to tell which links have been visited is by comparing the links in a document to the user's browser history. So, there are actually two basic types of anchors: visited and unvisited. These types are known as pseudo-classes, and the selectors that use them are called pseudo-class selectors.To better understand these classes and selectors, consider how browsers behave with regard to links. The Mosaic convention designated that links to pages you hadn't visited were blue, and links to already visited pages were red (the red became purple in succeeding browsers such as Internet Explorer). So, if you could insert classes into anchors, such that any already visited anchor would have a class of, say, "visited," then you could write a style to make such anchors red:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Summary
- InhaltsvorschauBy using selectors based on the document's language, authors can create CSS rules that apply to a large number of similar elements just as easily as they can construct rules that apply in very narrow circumstances. The ability to group together both selectors and rules keeps style sheets compact and flexible, which incidentally leads to smaller file sizes and faster download times.Selectors are the one thing that user agents usually must get right because the inability to correctly interpret selectors pretty much prevents a user agent from using CSS at all. On the flip side, it's crucial for authors to correctly write selectors because errors can prevent the user agent from applying the styles as intended. An integral part of correctly understanding selectors and how they can be combined is a strong grasp of how selectors relate to document structure and how mechanisms—such as inheritance and the cascade itself—come into play when determining how an element will be styled. This is the subject of the next chapter.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Chapter 3: Structure and the Cascade
- InhaltsvorschauChapter 2 shows how document structure and CSS selectors allow you to apply a wide variety of styles to elements. Knowing that every valid document generates a structural tree, you can create selectors that target elements based on their ancestors, attributes, sibling elements, and more. The structural tree is what allows selectors to function and is also central to a similarly crucial aspect of CSS: inheritance.Inheritance is the mechanism by which some property values are passed on from an element to its descendants. When determining which values should apply to an element, a user agent must consider not only inheritance but also the specificity of the declarations, as well as the origin of the declarations themselves. This process of consideration is what's known as the cascade. We will explore the interrelation between these three mechanisms—specificity, inheritance, and the cascade—in this chapter.Above all, regardless of how abstract things may seem, keep going! Your perseverance will be rewarded.You know from Chapter 2 that you can select elements using a wide variety of means. In fact, it's possible that the same element could be selected by two or more rules, each with its own selector. Let's consider the following three pairs of rules. Assume that each pair will match the same element:
h1 {color: red;} body h1 {color: green;} h2.grape {color: purple;} h2 {color: silver;} html > body table tr[id="totals"] td ul > li {color: maroon;} li#answer {color: navy;}Obviously, only one of the two rules in each pair can win out, since the matched elements can be only one color or the other. How do you know which one will win?The answer is found in the specificity of each selector. For every rule, the user agent evaluates the specificity of the selector and attaches it to each declaration in the rule. When an element has two or more conflicting property declarations, the one with the highest specificity will win out.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Specificity
- InhaltsvorschauYou know from Chapter 2 that you can select elements using a wide variety of means. In fact, it's possible that the same element could be selected by two or more rules, each with its own selector. Let's consider the following three pairs of rules. Assume that each pair will match the same element:
h1 {color: red;} body h1 {color: green;} h2.grape {color: purple;} h2 {color: silver;} html > body table tr[id="totals"] td ul > li {color: maroon;} li#answer {color: navy;}Obviously, only one of the two rules in each pair can win out, since the matched elements can be only one color or the other. How do you know which one will win?The answer is found in the specificity of each selector. For every rule, the user agent evaluates the specificity of the selector and attaches it to each declaration in the rule. When an element has two or more conflicting property declarations, the one with the highest specificity will win out.This isn't the whole story in terms of conflict resolution. In fact, all style conflict resolution is handled by the cascade, which has its own section later in this chapter.A selector's specificity is determined by the components of the selector itself. A specificity value is expressed in four parts, like this:0,0,0,0. The actual specificity of a selector is determined as follows:- For every ID attribute value given in the selector, add
0,1,0,0. - For every class attribute value, attribute selection, or pseudo-class given in the selection, add
0,0,1,0. - For every element and pseudo-element given in the selector, add
0,0,0,1. CSS2 contradicted itself as to whether pseudo-elements had any specificity at all, but CSS2.1 makes it clear that they do, and this is where they belong. - Combinators and the universal selector do not contribute anything to the specificity (more on these values later).
For example, the following rules' selectors result in the indicated specificities:h1 {color: red;} /* specificity = 0,0,0,1 */ p em {color: purple;} /* specificity = 0,0,0,2 */ .grape {color: purple;} /* specificity = 0,0,1,0 */ *.bright {color: yellow;} /* specificity = 0,0,1,0 */ p.bright em.dark {color: maroon;} /* specificity = 0,0,2,2 */ #id216 {color: blue;} /* specificity = 0,1,0,0 */ div#sidebar *[href] {color: silver;} /* specificity = 0,1,1,1 */Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Inheritance
- InhaltsvorschauAs important as specificity may be to understanding how declarations are applied to a document, another key concept is inheritance. Inheritance is the mechanism by which styles are applied not only to a specified element, but also to its descendants. If a color is applied to an
h1element, for example, then that color is applied to all text in theh1, even the text enclosed within child elements of thath1:h1 {color: gray;} <h1>Meerkat <em>Central</em></h1>Both the ordinaryh1text and theemtext are colored gray because theemelement inherits the value ofcolor. If property values could not be inherited by descendant elements, theemtext would be black, not gray, and you'd have to color that element separately.Inheritance also works well with unordered lists. Let's say you apply a style ofcolor:gray;forulelements:ul {color: gray;}You expect that a style that is applied to aulwill also be applied to its list items, and to any content of those list items. Thanks to inheritance, that's exactly what happens, as Figure 3-3 demonstrates.
Figure 3-3: Inheritance of stylesIt's easier to see how inheritance works by turning to a tree diagram of a document. Figure 3-4 shows the tree diagram for a very simple document containing two lists: one unordered and the other ordered.
Figure 3-4: A simple tree diagramWhen the declarationcolor:gray;is applied to theulelement, that element takes on that declaration. The value is then propagated down the tree to the descendant elements and continues on until there are no more descendants to inherit the value. Values are never propagated upward; that is, an element never passes values up to its ancestors.There is an exception to the upward propagation rule in HTML: background styles applied to thebodyelement can be passed to thehtmlelement, which is the document's root element and therefore defines its canvas.Inheritance is one of those things about CSS that is so basic that you almost never think about it unless you have to. However, you should still keep a few things in mind.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - The Cascade
- InhaltsvorschauThroughout this chapter, we've skirted one rather important issue: what happens when two rules of equal specificity apply to the same element? How does the browser resolve the conflict? For example, say you have the following rules:
h1 {color: red;} h1 {color: blue;}Which one wins? Both have a specificity of0,0,0,1, so they have equal weight and should both apply. That simply can't be the case because the element can't be both red and blue. But which will it be?Finally, the name "Cascading Style Sheets" makes some sense. CSS is based on a method of causing styles to cascade together, which is made possible by combining inheritance and specificity. The cascade rules for CSS2.1 are simple enough:- Find all rules that contain a selector that matches a given element.
- Sort by explicit weight all declarations applying to the element. Those rules marked
!importantare given higher weight than those that are not. Sort by origin all declarations applying to a given element. There are three origins: author, reader, and user agent. Under normal circumstances, the author's styles win out over the reader's styles.!importantreader styles are stronger than any other styles, including!importantauthor styles. Both author and reader styles override the user agent's default styles. - Sort by specificity all declarations applying to a given element. Those elements with a higher specificity have more weight than those with lower specificity.
- Sort by order all declarations applying to a given element. The later a declaration appears in the style sheet or document, the more weight it is given. Declarations that appear in an imported style sheet are considered to come before all declarations within the style sheet that imports them.
To be perfectly clear about how this all works, let's consider three examples that illustrate the last three of the four cascade rules.Under the second rule, if two rules apply to an element, and one is markedEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Summary
- InhaltsvorschauPerhaps the most fundamental aspect of Cascading Style Sheets is the cascade itself—the process by which conflicting declarations are sorted out and from which the final document presentation is determined. Integral to this process is the specificity of selectors and their associated declarations, and the mechanism of inheritance.In the next chapter, we will look at the many types of units that are used to give property values their meaning. Once we have completed that discussion, the fundamentals will be out of the way, and you'll be ready to learn about the properties used to style documents.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Chapter 4: Values and Units
- InhaltsvorschauIn this chapter, we'll tackle the elements that are the basis for almost everything you can do with CSS: the units that affect the colors, distances, and sizes of a whole host of properties. Without units, you couldn't declare that a paragraph should be purple, or that an image should have 10 pixels of blank space around it, or that a heading's text should be a certain size. By understanding the concepts put forth here, you'll be able to learn and use the rest of CSS much more quickly.There are two types of numbers in CSS: integers ("whole" numbers) and reals fractional numbers). These number types serve primarily as the basis for other value types, but, in a few instances, raw numbers can be used as a value for a property.In CSS2.1, a real number is defined as an integer that is optionally followed by a decimal and fractional numbers. Therefore, the following are all valid number values: 15.5, -270.00004, and 5. Both integers and reals may be either positive or negative, although properties can (and often do) restrict the range of numbers they will accept.A percentage value is a calculated real number followed by a percentage sign (
%). Percentage values are nearly always relative to another value, which can be anything, including the value of another property of the same element, a value inherited from the parent element, or a value of an ancestor element. Any property that accepts percentage values will define any restrictions on the range of allowed percentage values, and will also define the degree to which the percentage is relatively calculated.One of the first questions every starting web author asks is, "How do I set colors on my page?" Under HTML, you have two choices: you could use one of a small number of colors with names, such asredorpurple, or employ a vaguely cryptic method using hexadecimal codes. Both of these methods for describing colors remain in CSS, along with some other—and, I think, more intuitive—methods.Assuming that you're content to pick from a small, basic set of colors, the easiest method is simply to use the name of the color you want. CSS calls these color choices, logically enough,Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Numbers
- InhaltsvorschauThere are two types of numbers in CSS: integers ("whole" numbers) and reals fractional numbers). These number types serve primarily as the basis for other value types, but, in a few instances, raw numbers can be used as a value for a property.In CSS2.1, a real number is defined as an integer that is optionally followed by a decimal and fractional numbers. Therefore, the following are all valid number values: 15.5, -270.00004, and 5. Both integers and reals may be either positive or negative, although properties can (and often do) restrict the range of numbers they will accept.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Percentages
- InhaltsvorschauA percentage value is a calculated real number followed by a percentage sign (
%). Percentage values are nearly always relative to another value, which can be anything, including the value of another property of the same element, a value inherited from the parent element, or a value of an ancestor element. Any property that accepts percentage values will define any restrictions on the range of allowed percentage values, and will also define the degree to which the percentage is relatively calculated.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Color
- InhaltsvorschauOne of the first questions every starting web author asks is, "How do I set colors on my page?" Under HTML, you have two choices: you could use one of a small number of colors with names, such as
redorpurple, or employ a vaguely cryptic method using hexadecimal codes. Both of these methods for describing colors remain in CSS, along with some other—and, I think, more intuitive—methods.Assuming that you're content to pick from a small, basic set of colors, the easiest method is simply to use the name of the color you want. CSS calls these color choices, logically enough, named colors.Contrary to what some browser makers might have you believe, you have a limited palette of valid named-color keywords. For example, you're not going to be able to choose "mother-of-pearl" because it isn't a defined color. As of CSS2.1, the CSS specification defines 17 color names. These are the 16 colors defined in HTML 4.01 plus orange:aqua
fuchsia
lime
olive
red
white
black
gray
maroon
orange
silver
yellow
blue
green
navy
purple
tealSo, let's say you want all first-level headings to be maroon. The best declaration would be:h1 {color: maroon;}Simple and straightforward, isn't it? Figure 4-1 shows a few more examples:h1 {color: gray;} h2 {color: silver;} h3 {color: black;}
Figure 4-1: Naming colorsOf course, you've probably seen (and maybe even used) color names other than the ones listed earlier. For example, if you specify:h1 {color: lightgreen;}Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Length Units
- InhaltsvorschauMany CSS properties, such as margins, depend on length measurements to properly display various page elements. It's no surprise, then, that there are a number of ways to measure length in CSS.All length units can be expressed as either positive or negative numbers followed by a label (although some properties will accept only positive numbers). You can also use real numbers—that is, numbers with decimal fractions, such as 10.5 or 4.561. All length units are followed by a two-letter abbreviation that represents the actual unit of length being specified, such as
in(inches) orpt(points). The only exception to this rule is a length of0(zero), which need not be followed by a unit.These length units are divided into two types: absolute length units and relative length units.We'll start with absolute units because they're easiest to understand, despite the fact that they're almost unusable in web design. The five types of absolute units are as follows:-
Inches (
in) - As you might expect, this notation refers to the inches you'd find on a ruler in the United States. (The fact that this unit is in the specification, even though almost the entire world uses the metric system, is an interesting insight into the pervasiveness of U.S. interests on the Internet—but let's not get into virtual sociopolitical theory right now.)
-
Centimeters (
cm) - Refers to the centimeters that you'd find on rulers the world over. There are 2.54 centimeters to an inch, and one centimeter equals 0.394 inches.
-
Millimeters (
mm) - For those Americans who are metric-challenged, there are 10 millimeters to a centimeter, so an inch equals 25.4 millimeters, and a millimeter equals 0.0394 inches.
-
Points (
pt) - Points are standard typographical measurements that have been used by printers and typesetters for decades and by word-processing programs for many years. Traditionally, there are 72 points to an inch (points were defined before widespread use of the metric system). Therefore, the capital letters of text set to 12 points should be one-sixth of an inch tall. For example,
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
Inches (
- URLs
- InhaltsvorschauIf you've written web pages, you're obviously familiar with URLs (or, in CSS2.1, URIs). Whenever you need to refer to one—as in the
@importstatement, which is used when importing an external style sheet—the general format is:url(protocol://server/pathname)
This example defines what is known as an absolute URL. By absolute, I mean a URL that will work no matter where (or rather, in what page) it's found, because it defines an absolute location in web space. Let's say that you have a server called www.waffles.org. On that server, there is a directory calledpix, and in this directory is an image waffle22.gif. In this case, the absolute URL of that image would be:http://www.waffles.org/pix/waffle22.gif
This URL is valid no matter where it is found, whether the page that contains it is located on the server www.waffles.org or web.pancakes.com.The other type of URL is a relative URL, so named because it specifies a location that is relative to the document that uses it. If you're referring to a relative location, such as a file in the same directory as your web page, then the general format is:url(pathname)This works only if the image is on the same server as the page that contains the URL. For argument's sake, assume that you have a web page located at http://www.waffles.org/syrup.html and that you want the image waffle22.gif to appear on this page. In that case, the URL would be:pix/waffle22.gif
This path works because the web browser knows that it should start with the place it found the web document and then add the relative URL. In this case, the pathname pix/waffle22.gif added to the server name http://www.waffles.org equals http://www.waffles.org/pix/waffle22.gif. You can almost always use an absolute URL in place of a relative URL; it doesn't matter which you use, as long as it defines a valid location.In CSS, relative URLs are relative to the style sheet itself, not to the HTML document that uses the style sheet. For example, you may have an external style sheet that imports another style sheet. If you use a relative URL to import the second style sheet, it must be relative to the first style sheet. As an example, consider an HTML document atEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - CSS2 Units
- InhaltsvorschauIn addition to what we've covered in CSS2.1, CSS2 contains a few extra units, all of which are concerned with aural style sheets (employed by those browsers that are capable of speech). These units were not included in CSS2.1, but since they may be part of future versions of CSS, we'll briefly discuss them here:
- Angle values
- Used to define the position from which a given sound should originate. There are three types of angles: degrees (
deg), grads (grad), and radians (rad). For example, a right angle could be declared as90deg,100grad, or1.57rad; in each case, the values are translated into degrees in the range 0 through 360. This is also true of negative values, which are allowed. The measurement-90degis the same as270deg. - Time values
- Used to specify delays between speaking elements. They can be expressed as either milliseconds (
ms) or seconds (s). Thus,100msand0.1sare equivalent. Time values cannot be negative, as CSS is designed to avoid paradoxes. - Frequency values
- Used to declare a given frequency for the sounds that speaking browsers can produce. Frequency values can be expressed as hertz (
Hz) or megahertz (MHz) and cannot be negative. The values' labels are case-insensitive, so10MHzand10Mhzare equivalent.
The only user agent known to support any of these values at this writing is Emacspeak, an aural style sheets implementation. See Chapter 14 for details on aural styles.In addition to these values, there is also an old friend with a new name. A URI is a Uniform Resource Identifier, which is sort of another name for a Uniform Resource Locator (URL). Both the CSS2 and CSS2.1 specifications require that URIs be declared with the formurl(...), so there is no practical change.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Summary
- InhaltsvorschauUnits and values cover a wide spectrum of areas, from length units to special keywords that describe effects (such as
underline) to color units to the location of files (such as images). For the most part, units are the one area that user agents get almost totally correct, but it's those few little bugs and quirks that can get you. Navigator 4.x's failure to interpret relative URLs correctly, for example, has bedeviled many authors and led to an overreliance on absolute URLs. Colors are another area where user agents almost always do well, except for a few little quirks here and there. The vagaries of length units, however, far from being bugs, are an interesting problem for any author to tackle.These units all have their advantages and drawbacks, depending upon the circumstances in which they're used. We've already seen some of these circumstances, and their nuances will be discussed in the rest of the book, beginning with the CSS properties that describe ways to alter how text is displayed.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 5: Fonts
- InhaltsvorschauAs the authors of the CSS specification clearly recognized, font selection is a popular (and crucial) feature. After all, how many pages are littered with dozens, or even hundreds, of
<FONT FACE="...">tags? In fact, the beginning of the "Font Properties" section of the specification begins with the sentence, "Setting font properties will be among the most common uses of style sheets."Despite that importance, however, there currently isn't a way to ensure consistent font use on the Web because there isn't a uniform way of describing fonts and variants of fonts. For example, the fonts Times, Times New Roman, and TimesNR may be similar or even the same, but how would a user agent know that? An author might specify "TimesNR" in a document, but what happens when a user views the document without that particular font installed? Even if Times New Roman is installed, the user agent has no way to know that the two are effectively interchangeable. And if you're hoping to force a certain font on a reader, forget it.Although CSS2 defined facilities for downloadable fonts, they weren't well implemented by web browsers, and a reader could always refuse to download fonts for performance reasons. CSS does not provide ultimate control over fonts any more than a word processor does; when someone else loads a Microsoft Office document you have created, its display will depend on that person's installed fonts. If she doesn't have the same fonts you do, then the document will look different. This is also true of documents designed using CSS.The problem of font naming becomes especially confusing once you enter the realm of font variants, such as bold or italic text. Most people know what italic text looks like, but few can explain how it's different from slanted text, even though there are differences. "Slanted" is not the only other term for italic-style text, either—for example, you'll find oblique, incline (or inclined), cursive, and kursiv, among others. Thus, one font may have a variant called something like TimesItalic, whereas another uses something like GeorgiaOblique. Although the two may be effectively equivalent as the "italic form" of each font, they are labeled quite differently. Similarly, the font variant termsEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Font Families
- InhaltsvorschauAlthough there are, as discussed earlier, a number of ways to label what is effectively the same font, CSS makes a valiant attempt to help user agents sort out the mess. After all, what we think of as a "font" may be composed of many variations to describe boldfacing, italic text, and so forth. For example, you're probably familiar with the font Times. However, Times is actually a combination of many variants, including TimesRegular, TimesBold, TimesItalic, TimesOblique, TimesBoldItalic, TimesBoldOblique, and so on. Each of these variants of Times is an actual font face, but Times, as we usually think of it, is a combination of all these variant faces. In other words, Times is actually a font family, not just a single font, even though most of us think about fonts as being single entities.In addition to each specific font family such as Times, Verdana, Helvetica, or Arial, CSS defines five generic font families:
- Serif fonts
- These fonts are proportional and have serifs. A font is proportional if all characters in the font have different widths due to their various sizes. For example, a lowercase i and a lowercase m are different widths. (This book's paragraph font is proportional, for example.) Serifs are the decorations on the ends of strokes within each character, such as little lines at the top and bottom of a lowercase l, or at the bottom of each leg of an uppercase A. Examples of serif fonts are Times, Georgia, and New Century Schoolbook.
- Sans-serif fonts
- These fonts are proportional and do not have serifs. Examples of sans-serif fonts are Helvetica, Geneva, Verdana, Arial, and Univers.
- Monospace fonts
- Monospace fonts are not proportional. These generally are used to emulate typewritten text, the output from an old dot-matrix printer, or an even older video-display terminal. In these fonts, each character is exactly the same width as all the others, so a lowercase i is the same width as a lowercase m. These fonts may or may not have serifs. If a font has uniform character widths, it is classified as monospace, regardless of the presence of serifs. Examples of monospace fonts are Courier, Courier New, and Andale Mono.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Font Weights
- InhaltsvorschauEven though you may not realize it, you're already familiar with font weights; boldfaced text is a very common example of an increased font weight. CSS gives you more control over weights, at least in theory, with the property
font-weight.Generally speaking, the heavier a font weight becomes, the darker and "more bold" a font appears. There are a great many ways to label a heavy font face. For example, the font family known as Zurich has a number of variants, such as Zurich Bold, Zurich Black, Zurich UltraBlack, Zurich Light, and Zurich Regular. Each of these uses the same basic font, but each has a different weight.So let's say that you want to use Zurich for a document, but you'd like to make use of all those different heaviness levels. You could refer to them directly through thefont-familyproperty, but you really shouldn't have to do that. Besides, it's no fun having to write a style sheet like this:h1 {font-family: 'Zurich UltraBlack', sans-serif;} h2 {font-family: 'Zurich Black', sans-serif;} h3 {font-family: 'Zurich Bold', sans-serif;} h4, p {font-family: Zurich, sans-serif;} small {font-family: 'Zurich Light', sans-serif;}Aside from the obvious tedium of writing such a style sheet, it works only if everyone has these fonts installed, and it's a pretty safe bet that most people don't. It would make far more sense to specify a single font family for the whole document and then assign different weights to various elements. You can do this, in theory, using the various values for the propertyEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Font Size
- InhaltsvorschauThe methods for determining font size are both very familiar and very different.In a fashion very similar to the
font-weightkeywordsbolderandlighter, the propertyfont-sizehas relative-size keywords calledlargerandsmaller. Much like what we saw with relative font weights, these keywords cause the computed value offont-sizeto move up and down a scale of size values, which you'll need to understand before you can explorelargerandsmaller. First, though, we need to examine how fonts are sized in the first place.In fact, the actual relation of thefont-sizeproperty to what you see rendered is determined by the font's designer. This relationship is set as an em square (some call it an em box) within the font itself. This em square (and thus the font size) doesn't have to refer to any boundaries established by the characters in a font. Instead, it refers to the distance between baselines when the font is set without any extra leading (line-heightin CSS). It is quite possible for fonts to have characters that are taller than the default distance between baselines. For that matter, a font might be defined such that all of its characters are smaller than its em square, as many fonts do. Some hypothetical examples are shown in Figure 5-9.
Figure 5-9: Font characters and em squaresThus, the effect offont-sizeis to provide a size for the em box of a given font. This does not guarantee that any of the actual displayed characters will be this size.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Styles and Variants
- InhaltsvorschauCompared with everything we've covered so far, this section is practically a no-brainer. The properties discussed herein are so straightforward, and the complexities are so minimal, that this discussion will probably come as a great relief. First, we'll talk about
font-style, and then move on tofont-variantbefore wrapping up with the font properties.font-styleis very simple: it's used to select betweennormaltext,italictext, andobliquetext. That's it! The only complication is in recognizing the difference betweenitalicandobliquetext and in understanding why browsers don't always give you a choice.The default value offont-styleis, as you can see,normal. This refers to "upright" text, which is probably best described as "text that is not italic or otherwise slanted." The vast majority of text in this book is upright, for instance. That leaves only an explanation of the difference betweenitalicandobliquetext. For that, it's easiest to refer to Figure 5-16, which illustrates the differences very clearly.
Figure 5-16: Italic and oblique text in detailBasically, italic text is a separate font face, with small changes made to the structure of each letter to account for the altered appearance. This is especially true of serif fonts, where, in addition to the fact that the text characters "lean," the serifs may be altered in an italic face. Oblique text, on the other hand, is simply a slanted version of the normal, upright text. Font faces with labels like "Italic," "Cursive," and "Kursiv" are usually mapped to theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Stretching and Adjusting Fonts
- InhaltsvorschauThere are two font properties that appear in CSS2, but not in CSS2.1. They've been dropped from CSS2.1 because, despite being in the specification for years, no browser has bothered to implement either one. The first allows for the horizontal stretching of fonts, and the second allows for intelligent scaling of substituted fonts when the author's first choice is not available. First, let's look at stretching.As you might expect from the value names, this property is used to make a font's characters fatter or skinnier. It behaves very much like the absolute-size keywords (e.g.,
xx-large) for thefont-sizeproperty, with a range of absolute values and two values that let the author alter a font's stretching up or down. For example, an author might decide to stress the text in a strongly emphasized element by stretching the font characters to be wider than their parent element's font characters, as shown in Figure 5-21:strong {font-stretch: wider;}
Figure 5-21: Stretching font charactersFigure 5-21 was altered using Photoshop, since web browsers do not supportfont-stretchas of this writing.The similarly unimplemented process of adjusting font size is a little more complicated.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - The font Property
- InhaltsvorschauAll of these properties are very sophisticated, of course, but using them all could get a little tedious:
h1 {font-family: Verdana, Helvetica, Arial, sans-serif; font-size: 30px; font-weight: 900; font-style: italic; font-variant: small-caps;} h2 {font-family: Verdana, Helvetica, Arial, sans-serif; font-size: 24px; font-weight: bold; font-style: italic; font-variant: normal;}Some of this problem could be solved by grouping selectors, but wouldn't it be easier to combine everything into a single property? Enterfont, which is the shorthand property for all the other font properties (and a little more besides).Generally speaking, afontdeclaration can have any one value from each of the listed font properties, or else a "system font" value (described in the section "Using System Fonts"). Therefore, the preceding example could be shortened as follows:h1 {font: italic 900 small-caps 30px Verdana, Helvetica, Arial, sans-serif;} h2 {font: bold normal italic 24px Verdana, Helvetica, Arial, sans-serif;}and have exactly the same effect (illustrated by Figure 5-24).
Figure 5-24: Typical font rulesI say that the styles "could be" shortened in this way because there are a few other possibilities, thanks to the relatively loose way in whichfontcan be written. If you look closely at the preceding example, you'll see that the first three values don't occur in the same order. In theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Font Matching
- InhaltsvorschauAs we've seen, CSS allows for the matching of font families, weights, and variants. This is all accomplished through font matching, which is a vaguely complicated procedure. Understanding it is important for authors who want to help user agents make good font selections when displaying their documents. I left it for the end of the chapter because it's not really necessary to understand how the font properties work, and some readers will probably want to skip this part and go on to the next chapter. If you're still interested, here's how font matching works.
- The user agent creates, or otherwise accesses, a database of font properties. This database lists the various CSS properties of all of the fonts to which the user agent has access. Typically, this will be all fonts installed on the machine, although there could be others (for example, the user agent could have its own built-in fonts). If the user agent encounters two identical fonts, it will simply ignore one of them.
- The user agent takes apart an element to which font properties have been applied and constructs a list of font properties necessary for the display of that element. Based on that list, the user agent makes an initial choice of a font family to use in displaying the element. If there is a complete match, then the user agent can use that font. Otherwise, it needs to do a little more work.
- A font is first matched against the
font-style. The keyworditalicis matched by any font that is labeled as either "italic" or "oblique." If neither is available, then the match fails. - The next match attempt is on
font-variant. Any font that is not labeled "small-caps" is assumed to benormal. A font can be matched tosmall-capsby any font that is labeled as "small-caps," by any font that allows the synthesis of a small-caps style, or by any font where lowercase letters are replaced by uppercase letters. - The next match is to
font-weight, which can never fail thanks to the wayfont-weightis handled in CSS (explained earlier in the chapter).
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Summary
- InhaltsvorschauAlthough authors cannot count on a specific font being used in a document, they can very easily specify generic font families to be used. This particular behavior is very well supported, since any user agent that didn't let authors (or even readers) assign fonts would quickly find itself out of favor.As for the other areas of font manipulation, support varies. Changing the size of fonts usually works well, but 20th-century implementations ranged from frustratingly simplistic to very nearly correct in this area. The frustration for authors is usually not the way in which font sizing is supported, but rather, in how a unit they want to use (points) can yield very different results in different media, or even in different operating systems and user agents. The dangers of using points are many, and using length units for web design is generally not a good idea. Percentages, em units, and ex units are usually best for changing font sizes, since these scale very well in all common display environments.The other frustration is likely the continued lack of a mechanism to specify fonts for downloading and use in a document. This means that authors are still dependent on the fonts available to the user, and therefore, they cannot predict what appearance that text will take.Speaking of styling text, there are ways to do it that don't involve fonts, which the next chapter will address.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Chapter 6: Text Properties
- InhaltsvorschauSure, a lot of web design involves picking the right colors and getting the coolest look for your pages, but when it comes right down to it, you probably spend more of your time worrying about where text will go and how it will look. Such concerns gave rise to HTML tags such as
<FONT>and<CENTER>, which allow you some measure of control over the appearance and placement of text.Because text is so important, there are many CSS properties that affect it in one way or another. What is the difference between text and fonts? Simply, text is the content, and fonts are used to display that content. Using text properties, you can affect the position of text in relation to the rest of the line, superscript it, underline it, and change the capitalization. You can even simulate, to a limited degree, the use of a typewriter's Tab key.Let's start with a discussion of how you can affect the horizontal positioning of text within a line. Think of these basic actions as the same types of steps you might take to create a newsletter or write a report.Indenting the first line of a paragraph on a web page is one of the most sought-after text-formatting effects. (Eliminating the blank line between paragraphs, which is discussed in Chapter 7, is a close second.) Some sites create the illusion of indented text by placing a small transparent image before the first letter in a paragraph, which shoves over the text. Other sites use the utterly nonstandardSPACERtag. Thanks to CSS, there's a better way to indent text, calledtext-indent.Usingtext-indent, the first line of any element can be indented by a given length—even if that length is negative. The most common use for this property is, of course, to indent the first line of paragraphs:p {text-indent: 3em;}Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Indentation and Horizontal Alignment
- InhaltsvorschauLet's start with a discussion of how you can affect the horizontal positioning of text within a line. Think of these basic actions as the same types of steps you might take to create a newsletter or write a report.Indenting the first line of a paragraph on a web page is one of the most sought-after text-formatting effects. (Eliminating the blank line between paragraphs, which is discussed in Chapter 7, is a close second.) Some sites create the illusion of indented text by placing a small transparent image before the first letter in a paragraph, which shoves over the text. Other sites use the utterly nonstandard
SPACERtag. Thanks to CSS, there's a better way to indent text, calledtext-indent.Usingtext-indent, the first line of any element can be indented by a given length—even if that length is negative. The most common use for this property is, of course, to indent the first line of paragraphs:p {text-indent: 3em;}This rule will cause the first line of any paragraph to be indented three ems, as shown in Figure 6-1.
Figure 6-1: Text indentingIn general, you can applytext-indentto any block-level element. You can't apply it to inline elements or on replaced elements such as images. However, if you have an image within the first line of a block-level element, like a paragraph, it will be shifted over with the rest of the text in the line.If you want to "indent" the first line of an inline element, you can create the effect with left padding or margin.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Vertical Alignment
- InhaltsvorschauNow that we've covered horizontal alignment, let's move on to vertical alignment. Since the construction of lines is covered in much more detail in Chapter 7, I'll just stick to a quick overview here.The
line-heightproperty refers to the distance between the baselines of lines of text rather than the size of the font, and it determines the amount by which the height of each element's box is increased or decreased. In the most basic cases, specifyingline-heightis a way to increase (or decrease) the vertical space between lines of text, but this is a misleadingly simple way of looking at howline-heightworks.line-heightcontrols the leading, which is the extra space between lines of text above and beyond the font's size. In other words, the difference between the value ofline-heightand the size of the font is the leading.When applied to a block-level element,line-heightdefines the minimum distance between text baselines within that element. Note that it defines a minimum, not an absolute value, and baselines of text can wind up being pushed further apart than the value ofline-height.line-heightdoes not affect layout for replaced elements, but it still applies to them. (This subtle mystery is explained in Chapter 7.)Section 6.2.1.1: Constructing a line
Every element in a line of text generates a content area, which is determined by the size of the font. This content area in turn generates anEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Word Spacing and Letter Spacing
- InhaltsvorschauNow that we've dealt with alignment, let's look at manipulating word and letter spacing. As usual, these properties have some nonintuitive issues.The
word-spacingproperty accepts a positive or negative length. This length is added to the standard space between words. In effect,word-spacingis used to modify inter-word spacing. Therefore, the default value ofnormalis the same as setting a value of zero (0).If you supply a positive length value, then the space between words will increase. Setting a negative value forword-spacingbrings words closer together:p.spread {word-spacing: 0.5em;} p.tight {word-spacing: -0.5em;} p.base {word-spacing: normal;} p.norm {word-spacing: 0;} <p class="spread">The spaces between words in this paragraph will be increased by 0.5em.</p> <p class="tight">The spaces between words in this paragraph will be decreased by 0.5em.</p> <p class="base">The spaces between words in this paragraph will be normal.</p> <p class="norm">The spaces between words in this paragraph will be normal.</p>Manipulating these settings has the effect shown in Figure 6-19.
Figure 6-19: Changing the space between wordsSo far, I haven't actually given you a precise definition of "word." In the simplest CSS terms, a "word" is any string of nonwhitespace characters that is surrounded by whitespace of some kind. This definition has no real semantic meaning; it simply assumes that a document contains words surrounded by one or more whitespace characters. A CSS-aware user agent cannot be expected to decide what is a valid word in a given language and what isn't. This definition, such as it is, meansEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Text Transformation
- InhaltsvorschauNow let's look at ways to manipulate the capitalization of text using the property
text-transform.The default valuenoneleaves the text alone and uses whatever capitalization exists in the source document. As their names imply,uppercaseandlowercaseconvert text into all upper- or lowercase characters. Finally,capitalizecapitalizes only the first letter of each word. Figure 6-24 illustrates each of these settings in a variety of ways:h1 {text-transform: capitalize;} strong {text-transform: uppercase;} p.cummings {text-transform: lowercase;} p.raw {text-transform: none;} <h1>The heading-one at the beginninG</h1> <p> By default, text is displayed in the capitalization it has in the source document, but <strong>it is possible to change this</strong> using the property 'text-transform'. </p> <p class="cummings"> For example, one could Create TEXT such as might have been Written by the late Poet e.e.cummings. </p> <p class="raw"> If you feel the need to Explicitly Declare the transformation of text to be 'none', that can be done as well. </p>
Figure 6-24: Various kinds of text transformationDifferent user agents may have different ways of deciding where words begin and, as a result, which letters are capitalized. For example, the text "heading-one" in theh1element, shown in Figure 6-24, could be rendered in one of two ways: "Heading-one" or "Heading-One." CSS does not say which is correct, so either is possible.You probably also noticed that the last letter in theh1element in Figure 6-24 is still uppercase. This is correct: when applying atext-transformofcapitalize, CSS only requires user agents to make sure the first letter of each word is capitalized. They can ignore the rest of the word.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Text Decoration
- InhaltsvorschauNext we come to
text-decoration, which is a fascinating property that offers a whole truckload of interesting behaviors.As you might expect,underlinecauses an element to be underlined, just like theUelement in HTML.overlinecauses the opposite effect—drawing a line across the top of the text. The valueline-throughdraws a line straight through the middle of the text, which is also known as strikethrough text and is equivalent to theSandstrikeelements in HTML.blinkcauses the text to blink on and off, just like the much-malignedblinktag supported by Netscape. Figure 6-26 shows examples of each of these values:p.emph {text-decoration: underline;} p.topper {text-decoration: overline;} p.old {text-decoration: line-through;} p.annoy {text-decoration: blink;} p.plain {text-decoration: none;}
Figure 6-26: Various kinds of text decorationIt's impossible to show the effect ofblinkin print, of course, but it's easy enough to imagine (perhaps all too easy). Incidentally, user agents are not required to supportblink, and as of this writing, Internet Explorer never has.The valuenoneturns off any decoration that might otherwise have been applied to an element. Usually, undecorated text is the default appearance, but not always. For example, links are usually underlined by default. If you want to suppress the underlining of hyperlinks, you can use the following CSS rule to do so:a {text-decoration: none;}If you explicitly turn off link underlining with this sort of rule, the only visual difference between the anchors and normal text will be their color (at least by default, though there's no ironclad guarantee that there will be a difference in their colors).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Text Shadows
- InhaltsvorschauCSS2 includes a property for adding drop shadows to text, but this property did not make it into CSS2.1 because no browser had implemented full support for it by the time CSS2.1 was completed. When you consider the effort necessary to make a web browser determine the outlines of text in an element and then compute one or more shadows—all of which would have to blend together without overlapping the text itself—the lack of drop shadows in the specification is perhaps understandable.The obvious default is to not have a drop shadow for text. Otherwise, it's theoretically possible to define one or more shadows. Each shadow is defined by a color and three length values. The color sets the shadow's color, of course, so it's possible to define green, purple, or even white shadows.The first two length values determine the offset distance of the shadow from the text, and the optional third length value defines the "blur radius" for the shadow. To define a green shadow offset five pixels to the right and half an em down from the text, with no blurring, you would write:
text-shadow: green 5px 0.5em;
Negative lengths cause the shadow to be offset to the left and upward from the original text.The blur radius is defined as the distance from the shadow's outline to the edge of the blurring effect. A radius of two pixels would result in blurring that fills the space between the shadow's outline and the edge of the blurring. The exact blurring method is not defined, so different user agents might employ different effects. As an example, the following styles might be rendered something like Figure 6-31:p.cl1 {color: black; text-shadow: silver 2px 2px 2px;} p.cl2 {color: white; text-shadow: 0 0 4px black;} p.cl3 {color: black; text-shadow: 1em 1em 5px gray, -1em -1em silver;}Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Summary
- InhaltsvorschauEven without altering the font in use, there are many ways to change the appearance of text. There are classic effects such as underlining, of course, but CSS also enables you to draw lines over text or through it, change the amount of space between words and letters, indent the first line of a paragraph (or other block-level element), align text to the left or right, and much more. You can even alter the amount of space between lines of text, although this operation is unexpectedly complicated and covered in more detail in Chapter 7.These behaviors are all relatively well supported, or else not supported at all. Full justification of text is a major one that is not well supported, and most user agents released during the 20th century exhibited bugs in the text decoration and vertical alignment, as well as line-height calculations. On the other hand, word and letter spacing almost always work correctly when they're supported, and text indentation has manifested only a few very small bugs. The same is true of the ability to alter capitalization, which is usually supported correctly.At a few points in this chapter, I mentioned that the layout of lines was a more complicated process than presented. The next chapter covers details of that process and a great deal more.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Chapter 7: Basic Visual Formatting
- InhaltsvorschauIn the previous chapters, we covered a great deal of practical information on how CSS handles text and fonts in a document. In this chapter, we'll look at the theoretical side of visual rendering, answering many of the questions we skipped earlier in the interest of addressing how CSS is implemented.Why is it necessary to spend an entire chapter on the theoretical underpinnings of visual rendering in CSS? The answer is that with a model as open and powerful as that contained within CSS, no book could hope to cover every possible way of combining properties and effects. You will obviously go on to discover new ways of using CSS for your own document effects.In the course of exploring CSS, you may encounter seemingly strange behaviors in user agents. With a thorough grasp of how the visual rendering model works in CSS, you'll be able to determine whether a behavior is a correct (though unexpected) consequence of the rendering engine CSS defines, or whether you've stumbled across a bug that needs to be reported.CSS assumes that every element generates one or more rectangular boxes, called element boxes. (Future versions of the specification may allow for nonrectangular boxes, but for now everything is rectangular.) Each element box has a content area at its core. The content area is surrounded by optional amounts of padding, borders, and margins. These items are considered optional because they could all be set to a width of zero, effectively removing them from the element box. An example content area is shown in Figure 7-1, along with the surrounding regions of padding, border, and margins.
Figure 7-1: The content area and its surroundingsEach of the margins, borders, and padding can be set using various properties, such asmargin-leftorborder-bottom. The content's background—a color or tiled image, for example—is also applied to the padding. The margins are always transparent, revealing the background of any parent elements. Padding cannot be a negative value, but margins can. We'll explore the effects of negative margins later in this chapter.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Basic Boxes
- InhaltsvorschauCSS assumes that every element generates one or more rectangular boxes, called element boxes. (Future versions of the specification may allow for nonrectangular boxes, but for now everything is rectangular.) Each element box has a content area at its core. The content area is surrounded by optional amounts of padding, borders, and margins. These items are considered optional because they could all be set to a width of zero, effectively removing them from the element box. An example content area is shown in Figure 7-1, along with the surrounding regions of padding, border, and margins.
Figure 7-1: The content area and its surroundingsEach of the margins, borders, and padding can be set using various properties, such asmargin-leftorborder-bottom. The content's background—a color or tiled image, for example—is also applied to the padding. The margins are always transparent, revealing the background of any parent elements. Padding cannot be a negative value, but margins can. We'll explore the effects of negative margins later in this chapter.Borders are generated using defined styles, such assolidorinset, and their colors are set using theborder-colorproperty. If no color is set, then the border takes on the foreground color of the element's content. For example, if the text of a paragraph is white, then any borders around that paragraph will be white unless the author explicitly declares a different border color. If a border style has gaps of some type, then the element's background is visible through those gaps. In other words, the border has the same background as the content and padding. Finally, the width of a border can never be negative.The various components of an element box can be affected by a number of properties, such aswidthorborder-right. Many of these properties will be used in this chapter, even though we haven't discussed them yet. The actual property definitions are given in Chapter 8, which builds on the concepts set forth in this chapter.You will, however, find differences in how various types of elements are formatted. Block-level elements are treated differently than inline-level elements, while floated and positioned elements have their own ways of behaving.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Block-Level Elements
- InhaltsvorschauBlock-level elements can behave in both predictable and surprising ways. The handling of element placement along the horizontal and vertical axes can differ, for example. To fully understand how block-level elements are handled, you must clearly understand a number of boundaries and areas. They are shown in detail in Figure 7-2.
Figure 7-2: The complete box modelIn general, thewidthof an element is defined as the distance from the left inner edge to the right inner edge, and theheightis the distance from the inner top to the inner bottom. Both of these properties can be applied to an element.The various widths, heights, padding, and margins combine to determine how a document is laid out. In most cases, the height and width of the document are automatically determined by the browser and are based on the available display region and other factors. Under CSS, of course, you can assert more direct control over the way elements are sized and displayed. You can select different effects for horizontal and vertical layouts, so we'll tackle them separately.Horizontal formatting is often more complex than you'd think. Part of the complexity has to do with howwidthaffects the width of the content area, not the entire visible element box. Consider the following example:<p style="width: 200px;">wideness?</p>
This line of code will make the paragraph's content 200 pixels wide. If you gave the element a background, this would be quite obvious. However, any padding, borders, or margins you specify are added to the width value. Suppose you do this:<p style="width: 200px; padding: 10px; margin: 20px;">wideness?</p>
The visible element box is now 220 pixels wide since you've added 10 pixels of padding to the right and left of the content. The margins will now extend another 20 pixels to both sides for an overall element box width of 260 pixels.Understanding the hidden additions towidthis critical. Most users think thatwidthrefers to the width of the visible element box, and that if they declare an element to have padding, borders, and a width, the value they supply for the width will be the distance from the outer left border edge to the outer right border edge.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Inline Elements
- InhaltsvorschauAfter block-level elements, inline elements are the most common. Setting box properties for inline elements takes us into more interesting territory than we've visited so far. Some good examples of inline elements are the
emtag and theatag, both of which are nonreplaced elements, and images, which are replaced elements.None of the behavior described in this section applies to table elements. CSS2 introduced new properties and behaviors for handling tables and table content, and these elements behave in ways fairly distinct from either block-level or inline formatting. Table styling is discussed in Chapter 11.Nonreplaced and replaced elements are treated somewhat differently in the inline context, and we'll look at each in turn as we explore the construction of inline elements.First, you need to understand how inline content is laid out. It isn't as simple and straightforward as block-level elements, which just generate boxes and usually don't allow anything to coexist with them. By contrast, look inside a block-level element, such as a paragraph. You may well ask, "How did all those lines of text get there? What controls their arrangement? How can I affect it?"To understand how lines are generated, first consider the case of an element containing one very long line of text, as shown in Figure 7-27. Note that you've put a border around the line by wrapping the entire line in aspanelement and then assigning it a border style:span {border: 1px dashed black;}
Figure 7-27: A single-line inline elementFigure 7-27 shows the simplest case of an inline element contained by a block-level element. It's no different, in its own way, than a paragraph with two words in it. The only differences are that, in Figure 7-27, you have a few dozen words and most paragraphs don't contain an explicit inline element such asspan.To get from this simplified state to something more familiar, all you have to do is determine how wide the element should be, and then break up the line so that the resulting pieces will fit into the width of the element. Therefore, we arrive at the state shown in Figure 7-28.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Altering Element Display
- InhaltsvorschauAs I mentioned briefly in Chapter 1, you can affect the way a user agent displays by setting a value for the property
display. Now that we've taken a close look at visual formatting, let's revisit thedisplayproperty and discuss two more of its values using concepts from this chapter.We'll ignore the table-related values, since they are covered in Chapter 11, and we'll also ignore the valuelist-itemsince I deal with lists in detail in Chapter 12. We've spent quite some time discussingblockandinlineelements, but let's spend a moment talking about how altering an element's display role can alter layout before we look atinline-blockandrun-in.When it comes to styling a document, it's obviously handy to be able to change the display role of an element. For example, suppose you have a series of links in adivthat you'd like to lay out as a vertical sidebar:<div id="navigation"> <a href="index.html">WidgetCo Home</a><a href="products.html">Products</a> <a href="services.html">Services</a><a href="fun.html">Widgety Fun!</a> <a href="support.html">Support</a><a href="about.html" id="current">About Us</a> <a href="contact.html">Contact</a> </div>
You could put all the links into table cells, or wrap each one in its ownEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Summary
- InhaltsvorschauAlthough some aspects of the CSS formatting model may seem counterintuitive at first, they begin to make sense as you work with them more. In many cases, rules that initially seem nonsensical or even idiotic turn out to prevent bizarre or otherwise undesirable document displays. Block-level elements are in many ways easy to understand, and affecting their layout is typically a simple task. Inline elements, on the other hand, can be tricky to manage, as a number of factors come into play—not least of which is whether the element is replaced or nonreplaced. Now that we've established the underpinnings of document layout, let's turn our attention to how the various layout properties are used. This effort will span several chapters, and we'll start with the most common box properties: padding, borders, and margins.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Chapter 8: Padding, Borders, and Margins
- InhaltsvorschauIf you're like the vast majority of web designers who were working in the late 1990s, your pages all use tables for layout. You design them this way, of course, because tables can be used to create sidebars and to set up a complicated structure for an entire page's appearance. You might even use tables for simpler tasks, like putting text in a colored box with a border. When you think about it, though, you shouldn't need a table for such simple tasks. If you want only a paragraph with a red border and a yellow background, shouldn't creating it be easier than wrapping a single-cell table around it?The authors of CSS felt it should indeed be easier, so they devoted a great deal of attention to allowing you to define borders for paragraphs, headings,
divs, anchors, images—darned near everything a web page can contain. These borders can set an element apart from others, accentuate its appearance, mark certain kinds of data as having been changed, or any number of other things.CSS also lets you define regions around an element that control how the border is placed in relation to the content and how close other elements can get to that border. Between the content of an element and its border, we find the padding of an element, and beyond the border, the margins. These properties affect how the entire document is laid out, of course, but more importantly, they very deeply affect the appearance of a given element.As we discussed in Chapter 7, all document elements generate a rectangular box called the element box, which describes the amount of space that an element occupies in the layout of the document. Therefore, each box influences the position and size of other element boxes. For example, if the first element box in the document is an inch tall, the next box will begin at least an inch below the top of the document. If the first element box is changed to two inches tall, every following element box will shift downward an inch, and the second element box will begin at least two inches below the top of the document, as shown in Figure 8-1.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Basic Element Boxes
- InhaltsvorschauAs we discussed in Chapter 7, all document elements generate a rectangular box called the element box, which describes the amount of space that an element occupies in the layout of the document. Therefore, each box influences the position and size of other element boxes. For example, if the first element box in the document is an inch tall, the next box will begin at least an inch below the top of the document. If the first element box is changed to two inches tall, every following element box will shift downward an inch, and the second element box will begin at least two inches below the top of the document, as shown in Figure 8-1.
Figure 8-1: How one element affects all elementsBy default, a visually rendered document is composed of a number of rectangular boxes that are distributed such that they don't overlap one another. Also, within certain constraints, these boxes take up as little space as possible, while maintaining a sufficient separation to make clear which content belongs to which element.Boxes can overlap if they have been manually positioned, and visual overlap can occur if negative margins are used on normal-flow elements.To fully understand how margins, padding, and borders are handled, you must clearly understand the box model (also explained in Chapter 7). For reference, I'll include the box model diagram from that chapter (see Figure 8-2).
Figure 8-2: The CSS box modelAs Figure 8-2 illustrates, thewidthof an element is defined as the distance from the left inner edge to the right inner edge, and theheightis the distance from the inner top to the inner bottom.One important note about these two properties: they don't apply to inline nonreplaced elements. For example, if you try to declare aheightandwidthfor a hyperlink, CSS-conformant browsers must ignore those declarations. Assume that the following rule applies:a:link {color: red; background: silver; height: 15px; width: 60px;}You'll end up with red links on a silver background whose height and width are determined by the content of the links. They willEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Margins
- InhaltsvorschauThe separation between most normal-flow elements occurs because of element margins. Setting a margin creates extra "blank space" around an element. "Blank space" generally refers to an area in which other elements cannot also exist and in which the parent element's background is visible. For example, Figure 8-4 shows the difference between two paragraphs without any margins, and the same two paragraphs with margins.
Figure 8-4: Paragraphs with and without marginsThe simplest way to set a margin is by using the propertymargin.The effects of settingautomargins were discussed in detail in Chapter 7, so we won't repeat them here. Besides, it's more common to set length values for margins. Suppose you want to set a quarter-inch margin onh1elements, as illustrated in Figure 8-5. (A background color has been added so you can clearly see the edges of the content area.)
Figure 8-5: Setting a margin for h1 elementsh1 {margin: 0.25in; background-color: silver;}This sets a quarter-inch of blank space on each side of anh1element. In Figure 8-5, dashed lines represent the blank space, but the lines are purely illustrative and would not actually appear in a web browser.margincan accept any length of measurement, whether in pixels, inches, millimeters, or ems. However, the default value formarginis effectively0(zero), so if you don't declare a value, no margin should appear.In practice, however, browsers come with preassigned styles for many elements, and margins are no exception. For example, in CSS-enabled browsers, margins generate the "blank line" above and below each paragraph element. Therefore, if you don't declare margins for theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Borders
- InhaltsvorschauInside the margins of an element are its borders. The border of an element is simply one or more lines that surround the content and padding of an element. Thus, the background of the element will stop at the outer border edge, since the background does not extend into the margins, and the border is just inside the margin.Every border has three aspects: its width, or thickness; its style, or appearance; and its color. The default value for the width of a border is
medium, which is not explicitly defined but is usually two pixels. Despite this, the reason you don't usually see borders is that the default style isnone, which prevents them from existing. If a border has no style, it doesn't need to exist. (This lack of existence can also reset the width value, but we'll get to that in a little while.)Finally, the default border color is the foreground color of the element itself. If no color has been declared for the border, it will be the same color as the text of the element. If, on the other hand, an element has no text—let's say it has a table that contains only images—the border color for that table will be the text color of its parent element (due to the fact that color is inherited). That element is likely to bebody,div, or anothertable. Thus, if atablehas a border, and thebodyis its parent, given this rule:body {color: purple;}by default, the border around thetablewill be purple (assuming the user agent doesn't set a color for tables). Of course, to get that border to appear, you have to do a little work first.The CSS specification strongly implies that the background of an element extends to the outside edge of the border, since it mentions borders being drawn "on top of the background of the element." This is important because some borders are "intermittent"—for example, dotted and dashed borders—and the element's background should appear in the spaces between the visible portions of the border.When CSS2 was released, it stated that the background extends only into the padding, not the borders. This was later corrected, and CSS2.1 explicitly states that the element's background is the background of the content, padding, and border areas. Most browsers are in agreement with the CSS2.1 definition, although some older browsers may act differently. Background color issues are discussed in more detail in Chapter 9.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Padding
- InhaltsvorschauBetween the borders and the content area, we find the padding of the element box. It is no surprise that the simplest property used to affect this area is called
padding.As you can see, this property accepts any length value or a percentage value. So if you want allh1elements to have 10 pixels of padding on all sides, it's this easy:h1 {padding: 10px; background-color: silver;}On the other hand, you might wanth1elements to have uneven padding andh2elements to have regular padding:h1 {padding: 10px 0.25em 3ex 3cm;} /* uneven padding */ h2 {padding: 0.5em 2em;} /* values replicate to the bottom and left sides */It's a little tough to see the padding if that's all you add, though, so let's include a background color, as shown in Figure 8-38:h1 {padding: 10px 0.25em 3ex 3cm; background: gray;} h2 {padding: 0.5em 2em; background: silver;}
Figure 8-38: Uneven padding with background colorsAs Figure 8-38 illustrates, the background of an element extends into the padding. As we discussed before, it also extends to the outer edge of the border, but the background has to go through the padding before it even gets to the border.By default, elements have no padding. The separation between paragraphs, for example, has traditionally been enforced with margins alone. It's also the case that, without padding, a border on an element will come very close to the content of the element itself. Thus, when putting a border on an element, it's usually a good idea to add some padding as well, as Figure 8-39 illustrates.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Summary
- InhaltsvorschauThe ability to apply margins, borders, and padding to any element is one of the things that sets CSS so far above traditional web markup. In the past, enclosing a heading in a colored, bordered box meant wrapping the heading in a table, which is a really bloated and awful way to create such a simple effect. It is this sort of power that makes CSS so compelling.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Chapter 9: Colors and Backgrounds
- InhaltsvorschauRemember the first time you changed the colors of a web page? Instead of the old black text on a gray background with blue links, all of a sudden you could use any combination of colors you desired—perhaps light blue text on a black background with lime-green hyperlinks. From there, it was just a short hop to colored text and, eventually, even to multiple colors for the text in a page, thanks to
<FONT COLOR=" . . . ">. Once you could add background images, too, just about anything was possible, or so it seemed. CSS takes color and backgrounds even further, letting you apply many different colors and backgrounds to a single page, and all without a singleFONTorTABLEtag.When designing a page, you need to plan it out before you start. That's generally true in any case, but with colors, it's even more so. If you're going to make all hyperlinks yellow, will they clash with the background color in any part of your document? If you use too many colors, will it overwhelm the user? (Hint: yes.) If you change the default hyperlink colors, will users still be able to figure out where your links are? (For example, if you make both regular text and hyperlink text the same color, it's much harder to spot links—in fact, almost impossible if the links aren't underlined.)Despite the added planning, the ability to change the colors of elements is something almost every author will want to use, probably quite often. Used properly, colors can really strengthen the presentation of a document. As an example, let's say you have a design where allh1elements should be green, mosth2elements should be blue, and all hyperlinks should be dark red. In some cases, however, you wanth2elements to be dark blue because they're associated with different types of information. The simplest way to handle this is to assign a class to eachh2that should be dark blue and declare the following:h1 {color: green;} h2 {color: blue;} h2.dkblue {color: navy;} a {color: maroon;} /* a good dark red color */It's actually better to pick class names that describe the type of information contained within, not the visual effect you're trying to achieve. For example, let's say that you want dark blue to be applied to allEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Colors
- InhaltsvorschauWhen designing a page, you need to plan it out before you start. That's generally true in any case, but with colors, it's even more so. If you're going to make all hyperlinks yellow, will they clash with the background color in any part of your document? If you use too many colors, will it overwhelm the user? (Hint: yes.) If you change the default hyperlink colors, will users still be able to figure out where your links are? (For example, if you make both regular text and hyperlink text the same color, it's much harder to spot links—in fact, almost impossible if the links aren't underlined.)Despite the added planning, the ability to change the colors of elements is something almost every author will want to use, probably quite often. Used properly, colors can really strengthen the presentation of a document. As an example, let's say you have a design where all
h1elements should be green, mosth2elements should be blue, and all hyperlinks should be dark red. In some cases, however, you wanth2elements to be dark blue because they're associated with different types of information. The simplest way to handle this is to assign a class to eachh2that should be dark blue and declare the following:h1 {color: green;} h2 {color: blue;} h2.dkblue {color: navy;} a {color: maroon;} /* a good dark red color */It's actually better to pick class names that describe the type of information contained within, not the visual effect you're trying to achieve. For example, let's say that you want dark blue to be applied to allh2elements that are subsection headings. It's preferable to pick a class name likesubsecor evensub-section, which actually mean something and, more importantly, are independent of any presentational concepts. After all, you might decide later to make all subsection titles dark red instead of dark blue, and the statementh2.dkblue {color:maroon;}is more than a little silly.From this simple example, you can see that it's generally better to plan ahead when you're using styles, so you can use all of the tools at your disposal. For example, suppose you add a navigational bar to the page in the preceding example. Within this bar, hyperlinks should be yellow, not dark red. If the bar is marked with an ID ofEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Foreground Colors
- InhaltsvorschauThe easiest way to set the foreground color of an element is with the property
color.As discussed in Chapter 4, this property accepts as a value any valid color type, such as#FFCC00orrgb(100%,80%,0%), as well as the system-color keywords described in Chapter 13.For nonreplaced elements,colorsets the color of the text in the element, as illustrated in Figure 9-1:<p style="color: gray;">This paragraph has a gray foreground.</p> <p>This paragraph has the default foreground.</p>
Figure 9-1: Declared color versus default colorIn Figure 9-1, the default foreground color is black. That isn't always the case since users might have set their browsers (or other user agents) to use a different foreground (text) color. If the default text were set to green, the second paragraph in the preceding example would be green, not black—but the first paragraph would still be gray.You need not restrict yourself to such simple operations, of course. There are plenty of ways to use color. You might have some paragraphs that contain text warning the user of a potential problem. To make this text stand out, you might decide to color it red. Simply apply aclassofwarnto each paragraph that contains warning text (<p class="warn">) and the following rule:p.warn {color: red;}In the same document, you might decide that any unvisited links within a warning paragraph should be green:p.warn {color: red;} p.warn a:link {color: green;}Then you change your mind, deciding that warning text should be dark gray and that links in such text should be medium gray. The preceding rules need only be changed to reflect the new values, as illustrated in Figure 9-2:p.warn {color: #666;} p.warn a:link {color: #AAA;}Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Backgrounds
- InhaltsvorschauThe background area of an element consists of all of the space behind the foreground to the outer edge of the borders; thus, the content box and the padding are all part of an element's background, and the borders are drawn on top of the background.CSS lets you apply a solid color or create moderately sophisticated effects using background images; its capabilities in this area far outstrip those of HTML.It's possible to declare a color for the background of an element, in a fashion very similar to setting the foreground color. For this, use the property
background-color, which accepts (unsurprisingly) any valid color or a keyword that makes the background transparent.If you want the color to extend a little bit from the text in the element, simply add some padding to the mix, as illustrated in Figure 9-8:p {background-color: gray; padding: 10px;}
Figure 9-8: Backgrounds and paddingYou can set a background color for just about any element, frombodyall the way down to inline elements such asemanda.background-coloris not inherited. Its default value istransparent, which makes sense: if an element doesn't have a defined color, then its background should be transparent so that the background of its ancestor elements will be visible.One way to picture the inheritance situation is to imagine a clear plastic sign mounted to a textured wall. The wall is still visible through the sign, but this is not the background of the sign, it's the background of the wall (in CSS terms, anyway). Similarly, if you set the canvas to have a background, it can be seen through all of the elements in the document that don't have their own backgrounds. They don't inherit the background; it is visibleEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Summary
- InhaltsvorschauSetting colors and backgrounds on elements gives authors a great deal of power. The advantage of CSS over traditional methods is that colors and backgrounds can be applied to any element in a document—not just table cells, for example, or anything enclosed in a
FONTtag. Despite a few bugs in some implementations, such as Navigator 4's reluctance to apply a background to the entire content area of an element, backgrounds are very widely used properties. Their popularity isn't too hard to understand, either, since color is one easy way to distinguish the look of one page from another.CSS allows for a great deal more in the way of element styling, however: borders that can be placed on any element, extra margins and padding, and even a way to "float" elements other than images. We'll get into these concepts in the next chapter.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 10: Floating and Positioning
- InhaltsvorschauSure, CSS makes content look good with font changes, backgrounds, and all the rest, but what about accomplishing basic layout tasks? Enter floating and positioning. These are the tools by which you can set up columnar layout, overlap one piece of layout with another, and generally accomplish everything that so many tables have been used for over the years.The idea behind positioning is fairly simple. It allows you to define exactly where element boxes will appear relative to where they would ordinarily be—or relative to a parent element, another element, or even to the browser window itself. The power of this feature is both obvious and surprising. It shouldn't shock you to learn that user agents support this element of CSS2 better than many others.Floating, on the other hand, was first offered in CSS1, based on a capability that had been added by Netscape early in the Web's life. Floating is not exactly positioning, but it certainly isn't normal-flow layout either. We'll see exactly what this means later in the chapter.You are almost certainly acquainted with the concept of floated elements. Ever since Netscape 1, it has been possible to float images by declaring, for instance,
<img src="b5.gif" align="right">. This causes an image to float to the right and allows other content (such as text) to "flow around" the image. The name "floating," in fact, comes from the document "Extensions to HTML 2.0," which stated:The additions to your ALIGN options need a lot of explanation. First, the values "left" and "right". Images with those alignments are an entirely new floating image type.In the past, it was only possible to float images and, in some browsers, tables. CSS, on the other hand, lets you float any element, from images to paragraphs to lists. In CSS, this behavior is accomplished using the propertyfloat.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Floating
- InhaltsvorschauYou are almost certainly acquainted with the concept of floated elements. Ever since Netscape 1, it has been possible to float images by declaring, for instance,
<img src="b5.gif" align="right">. This causes an image to float to the right and allows other content (such as text) to "flow around" the image. The name "floating," in fact, comes from the document "Extensions to HTML 2.0," which stated:The additions to your ALIGN options need a lot of explanation. First, the values "left" and "right". Images with those alignments are an entirely new floating image type.In the past, it was only possible to float images and, in some browsers, tables. CSS, on the other hand, lets you float any element, from images to paragraphs to lists. In CSS, this behavior is accomplished using the propertyfloat.For example, to float an image to the left, you could use this markup:<img src="b4.gif" style="float: left;" alt="b4">
As Figure 10-1 makes clear, the image "floats" to the left side of the browser window, and the text flows around it. This is just what you should expect.
Figure 10-1: A floating imageHowever, when floating elements in CSS, some interesting issues come up.Keep a few things in mind with regard to floating elements. First, a floated element is, in some ways, removed from the normal flow of the document, although it still affects the layout. In a manner utterly unique within CSS, floated elements exist almost on their own plane, yet they still have influence over the rest of the document.This influence derives from the fact that when an element is floated, other content "flows around" it. This is familiar behavior with floated images, but the same is true if you float a paragraph, for example. In Figure 10-2, you can see this effect quite clearly, thanks to the margin added to the floated paragraph:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Positioning
- InhaltsvorschauThe idea behind positioning is fairly simple. It allows you to define exactly where element boxes will appear relative to where they would ordinarily be—or relative to a parent element, another element, or even to the browser window itself.Before we delve into the various kinds of positioning, it's a good idea to look at what types exist and how they differ. We'll also need to define some basic ideas that are fundamental to understanding how positioning works.
Section 10.2.1.1: Types of positioning
You can choose one of four different types of positioning, which affect how the element's box is generated, by using thepositionproperty.The values ofpositionhave the following meanings:-
static - The element's box is generated as normal. Block-level elements generate a rectangular box that is part of the document's flow, and inline-level boxes cause the creation of one or more line boxes that are flowed within their parent element.
-
relative - The element's box is offset by some distance. The element retains the shape it would have had were it not positioned, and the space that it would ordinarily have occupied is preserved.
-
absolute - The element's box is completely removed from the flow of the document and positioned with respect to its containing block, which may be another element in the document or the initial containing block (described in the next section). Whatever space the element might have occupied in the normal document flow is closed up, as though the element did not exist. The positioned element generates a block-level box, regardless of the type of box it would have generated if it were in the normal flow.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Summary
- InhaltsvorschauFloating and positioning are very compelling features of CSS. They're also likely to be an exercise in frustration if you're careless in how you use them. Element overlapping, stacking order, size, and placement all have to be considered carefully when elements are positioned, and floated elements' relation to the normal flow must also be taken into account. Creating layouts using floating and positioning can thus take some adjustment, but the rewards are well worth the price.While it's true that a great deal of layout can thus be freed of tables, there are still reasons to use tables on the Web, such as presenting stock quotes or sports scores, among others. In the next chapter, we'll examine how CSS has grown to address the question of table layout.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Chapter 11: Table Layout
- InhaltsvorschauYou may have glanced at the title of this chapter and wondered, "Table layout? Isn't that exactly what we're trying to avoid doing?" Indeed so, but this chapter is not about using tables for layout. Instead, it's about the ways that tables themselves are laid out within CSS, which is a far more complicated affair than it might first appear. That's why the subject warrants its own chapter.Tables are unique, compared to the rest of document layout. As of CSS2.1, tables alone possess the ability to associate element sizes with other elements—all the cells in a row have the same height, for example, no matter how much or how little content each individual cell might contain. The same is true for the widths of cells that share a column. There is no other situation in layout where elements from different parts of the document tree influence one another's sizing and layout in such a direct way.As we'll see, this uniqueness comes at the expense of a great many behaviors and rules that apply to tables, and only tables. In the course of the chapter, we'll look at how tables are visually assembled, two different ways to draw cell borders, and the mechanisms that drive the height and width of tables and their internal elements.Before you can start to worry about how cell borders are drawn and tables sized, we need to delve into the fundamental ways in which tables are assembled, and the ways that elements within the table are related to one another. This is referred to as
table formatting, and it is quite distinct from table layout: the latter is possible only after the former has been completed.The first thing to understand is how CSS defines the arranging of tables. While this knowledge may seem a bit basic, it's key to understanding how best to style tables.CSS draws a distinction between table elements and internal table elements. In CSS, internal table elements generate rectangular boxes that have content, padding, and borders, but do not have margins. Therefore, it is not possible to define the separation between cells by giving them margins. A CSS-conformant browser will ignore any attempts to apply margins to cells, rows, or any other internal table element (with the exception of captions, which are discussed later in this chapter).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Table Formatting
- InhaltsvorschauBefore you can start to worry about how cell borders are drawn and tables sized, we need to delve into the fundamental ways in which tables are assembled, and the ways that elements within the table are related to one another. This is referred to as
table formatting, and it is quite distinct from table layout: the latter is possible only after the former has been completed.The first thing to understand is how CSS defines the arranging of tables. While this knowledge may seem a bit basic, it's key to understanding how best to style tables.CSS draws a distinction between table elements and internal table elements. In CSS, internal table elements generate rectangular boxes that have content, padding, and borders, but do not have margins. Therefore, it is not possible to define the separation between cells by giving them margins. A CSS-conformant browser will ignore any attempts to apply margins to cells, rows, or any other internal table element (with the exception of captions, which are discussed later in this chapter).There are six rules for arranging tables. The basis of these rules is a "grid cell," which is one area between the grid lines on which a table is drawn. Consider Figure 11-1, in which two tables are shown along with their grid cells, which are indicated by the dashed lines drawn over the tables.
Figure 11-1: Grid cells form the basis of table layoutIn a simple two-by-two table, such as the lefthand table shown in Figure 11-1, the grid cells correspond to the cells. In a more complicated table, like the righthand one in Figure 11-1, the edges of the grid cells correspond to the cell borders of all the cells in the table, and cut through those cells that span rows or columns.These grid cells are largely theoretical constructs, and they cannot be styled or even accessed through the document object model. They simply serve as a way to describe how tables are assembled for styling.Section 11.1.1.1: Table arrangement rules
- Each row box encompasses a single row of grid cells. All of the row boxes in a table fill the table from top to bottom in the order they occur in the source document (with the exception of any table header or table footer row boxes, which come at the beginning and end of the table, respectively). Thus, the table contains as many grid rows as there are row elements.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Table Cell Borders
- InhaltsvorschauThere are actually two quite distinct border models in CSS. The separated border model takes effect when cells are separated from each other in layout terms. The other option is the collapsed border model, in which there is no visual separation between cells, and cell borders merge, or collapse, with each other. The former is the default model, although in an earlier version of CSS the latter was the default.An author can choose between the two models with the property
border-collapse.The whole point of this property is to offer the author a way to determine which border model the user agent will employ. If the valuecollapseis in effect, then the collapsing borders model is used. If the value isseparate, then the separated borders model is used. We'll look at the latter model first, since it's actually much simpler to describe.In this model, every cell in the table is separated from the other cells by some distance, and the borders of cells do not collapse into each other. Thus, given the following styles and markup, you would see the result shown in Figure 11-6:table {border-collapse: separate;} td {border: 3px double black; padding: 3px;} <table cellspacing="0"> <tr> <td>cell one</td> <td>cell two</td> </tr> <tr> <td>cell three</td> <td>cell four</td> </tr> </table>
Figure 11-6: Separated (and thus separate) cell bordersNote that the cell borders touch but remain distinct from one another. The three lines between cells are actually the two double borders sitting right next to each other.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Table Sizing
- InhaltsvorschauNow that we've delved into table formatting and cell border appearance, we have the pieces we need to understand the sizing of tables and their internal elements. When it comes to determining table width, there are two different approaches: fixed-width layout and automatic-width layout. Heights are calculated automatically no matter what width algorithms are used.Since there are two different ways to figure out the width of a table, it's only logical that there be a way to declare which should be used for a given table. Authors can use the property
table-layoutto select between the two kinds of table width calculation.While the two models can have different results in laying out a specific table, the more fundamental difference between the two is speed. With a fixed-width table layout, the user agent can calculate the layout of the table more quickly than is possible in the automatic-width model.Section 11.3.1.1: Fixed layout
The main reason the fixed-layout model is so fast is that its layout does not depend on the contents of table cells. Instead, it's driven by thewidthvalues of the table, columns, and cells within that table.The fixed-layout model works in the following simple steps:- Any column element whose
widthproperty has a value other thanautosets the width for that column. - If a column has an
autowidth, but the cell in the first row of the table within that column has awidthother thanauto, then the cell sets the width for that column. If the cell spans multiple columns, the width is divided between the columns.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Summary
- InhaltsvorschauEven if you're quite familiar with table layout from years of table-and-spacer design, the mechanisms driving such layout are rather complicated and not at all deterministic. Due to the legacy of HTML table construction, the CSS table model is row-centric, but it does, thankfully, accommodate columns and limited column styling. Thanks to new features that affect cell alignment and table width, you now have even more tools for presenting tables in a pleasing way.The ability to apply table-related
displayvalues to arbitrary elements opens the door to creating table-like layouts using HTML elements such asdiv, or in XML languages where any element could be used to describe layout components. As of this writing, most browsers other than Internet Explorer support the application of table-relateddisplayvalues to arbitrary elements. Even in its current form, CSS makes presentation more sophisticated, as does the subject of the next chapter: generated content.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 12: Lists and Generated Content
- InhaltsvorschauIn the realm of CSS layout, lists are an interesting case. The items in a list are simply block boxes, but with an extra bit that doesn't really participate in the document layout hanging off to one side. With an ordered list, that extra bit contains a series of increasing numbers (or letters) that are calculated and mostly formatted by the user agent, not the author. Taking a cue from the document structure, the user agent generates the numbers and their basic presentation.None of this content generation could be described in CSS1 terms—and, therefore, it couldn't be controlled—but CSS2 introduced features that allow list-item numbering to be described. As a result, CSS now lets you, the author, define your own counting patterns and formats, and associate those counters with any element, not just ordered list items. Furthermore, this basic mechanism makes it possible to insert other kinds of content, including text strings, attribute values, or even external resources into a document. Thus, it becomes possible to use CSS to insert link icons, editorial symbols, and more into a design without having to create extra markup.To see how all these list options fit together, we'll explore basic list styling before moving on to examine the generation of content and counters.In a sense, almost anything that isn't narrative text can be considered a list. The U.S. Census, the solar system, my family tree, a restaurant menu, and even all of the friends you've ever had can be represented as a list, or perhaps as a list of lists. These many variations make lists fairly important, which is why it's a shame that list styling in CSS isn't more sophisticated.The simplest (and best-supported) way to affect a list's styles is to change its marker type. The marker of a list item is, for example, the bullet that appears next to each item in an unordered list. In an ordered list, the marker could be a letter, number, or a symbol from some other counting system. You can even replace the markers with images. All of these are accomplished using the different list-style properties.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Lists
- InhaltsvorschauIn a sense, almost anything that isn't narrative text can be considered a list. The U.S. Census, the solar system, my family tree, a restaurant menu, and even all of the friends you've ever had can be represented as a list, or perhaps as a list of lists. These many variations make lists fairly important, which is why it's a shame that list styling in CSS isn't more sophisticated.The simplest (and best-supported) way to affect a list's styles is to change its marker type. The marker of a list item is, for example, the bullet that appears next to each item in an unordered list. In an ordered list, the marker could be a letter, number, or a symbol from some other counting system. You can even replace the markers with images. All of these are accomplished using the different list-style properties.To change the type of marker used for a list's items, use the property
list-style-type.That's quite a few keywords, I know; many of them were introduced in CSS2 but were then dropped in CSS2.1. Table 12-1 lists the keywords that exist in CSS2.1.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Generated Content
- InhaltsvorschauCSS2 and CSS2.1 include a new feature called generated content. This is content created by the browser but not represented either by markup or content.For example, list markers are generated content. There is nothing in the markup of a list item that directly represents the markers, and you, the author, do not have to write the markers into your document's content. The browser simply generates the appropriate marker automatically. For unordered lists, the marker is a bullet of some kind, such as a circle, disc, or square. In ordered lists, the marker is a counter that increments by one for each successive list item.To understand how you can affect list markers and customize the counting of ordered lists (or anything else!), you must first look at more basic generated content.As of this writing, no version of Internet Explorer supports generated content.To insert generated content into the document, use the
:beforeand:afterpseudo-elements. These place generated content before or after the content of an element by way of the content property (described in the next section).For example, you might want to precede every hyperlink with the text "(link)" to mark them for printing. This is accomplished with a rule like the following, which has the effect shown in Figure 12-11:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Summary
- InhaltsvorschauEven though list styling isn't as sophisticated as we might like, and browser support for generated content is somewhat spotty (as of this writing, anyway), the ability to style lists is still highly useful. One relatively common use is to take a list of links, remove the markers and indentation, and thus create a navigation sidebar. The combination of simple markup and flexible layout is difficult to resist. With the anticipated enhancements to list styling in CSS3, I expect that lists will become more and more useful.For now, in situations where a markup language doesn't have intrinsic list elements, generated content can be an enormous help—say, for inserting content such as icons to point to certain types of links (PDF files, Word documents, or even just links to another web site). Generated content also makes it easy to print out link URLs, and its ability to insert and format quotation marks leads to true typographic joy. It's safe to say that the usefulness of generated content is limited only by your imagination. Even better, thanks to counters, you can now associate ordering information to elements that are not typically lists, such as headings or code blocks. Now, if you want to support such features with design that mimics the appearance of the user's operating system, read on. The next chapter will discuss ways to use system colors and fonts in CSS design.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Chapter 13: User Interface Styles
- InhaltsvorschauThe vast majority of CSS is concerned with styling documents, but it offers a passel of useful interface-styling tools for more than just documents. For example, Mozilla's developers created its browser's interface (and that of many Mozilla clones) using a language called XUL. XUL employs CSS and CSS-like declarations to present the navigation buttons, sidebar tabs, dialog boxes, status boxes, and other pieces of the chrome itself.Similarly, you can reuse aspects of the user's default environment to style a document's fonts and colors; it's even possible to exert influence over focus highlighting and the mouse cursor. CSS2's interface capabilities can make the user's experience more enjoyable—or more confusing, if you aren't careful.There may be times when you want your document to mimic the user's computing environment as closely as possible. An obvious example is if you're creating web-based applications, where the goal is to make the web component seem like a part of the user's operating system. While CSS2 doesn't make it possible to reuse every last aspect of the operating system's appearance in your documents, you can choose from a wide variety of colors and a short list of fonts.Let's say you've created an element that functions as a button (via JavaScript, for example). By making the control look just like a button in the user's computing environment, you meet the user's expectations of how a control should look and thus make it more usable.To accomplish the given example, simply write a rule like this:
a.widget {font: caption;}This will set the font of anyaelement with aclassofwidgetto use the same font family, size, weight, style, and variant as the text found in captioned controls, such as a button.CSS2 defines six system font keywords. These are described in the following list:-
caption - The font styles used for captioned controls, such as buttons and drop-downs
-
icon - The font styles used to label operating system icons, such as hard drives, folders, and files
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- System Fonts and Colors
- InhaltsvorschauThere may be times when you want your document to mimic the user's computing environment as closely as possible. An obvious example is if you're creating web-based applications, where the goal is to make the web component seem like a part of the user's operating system. While CSS2 doesn't make it possible to reuse every last aspect of the operating system's appearance in your documents, you can choose from a wide variety of colors and a short list of fonts.Let's say you've created an element that functions as a button (via JavaScript, for example). By making the control look just like a button in the user's computing environment, you meet the user's expectations of how a control should look and thus make it more usable.To accomplish the given example, simply write a rule like this:
a.widget {font: caption;}This will set the font of anyaelement with aclassofwidgetto use the same font family, size, weight, style, and variant as the text found in captioned controls, such as a button.CSS2 defines six system font keywords. These are described in the following list:-
caption - The font styles used for captioned controls, such as buttons and drop-downs
-
icon - The font styles used to label operating system icons, such as hard drives, folders, and files
-
menu - The font styles used for text in drop-down menus and menu lists
-
message-box - The font styles used to present text in dialog boxes
-
small-caption - The font styles used for labeling small captioned controls
-
status-bar - The font styles used for text in window status bars
It's important to realize that these values can be used only with thefontproperty and are their own form of shorthand. For example, let's assume that a user's operating system shows icon labels as 10-pixel Geneva with no boldfacing, italicizing, or small-caps effects. This means that the following three rules are all equivalent, and have the result shown in Figure 13-1:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Cursors
- InhaltsvorschauAnother important part of the user interface is the cursor (referred to in the CSS specification as the "pointing device"), which is controlled by a device such as a mouse, trackpad, graphic tablet, or even an optical-reading system. The cursor is useful for providing interaction feedback in most web browsers; an obvious example is that the cursor changes to a small hand with an extended index finger whenever it crosses over a hyperlink.CSS2 lets you change the cursor icon, which means that it's much easier to create web-based applications that function in a manner similar to desktop applications in the operating system. For example, a link to help files might cause the cursor to turn into a "help" icon such as a question mark, as shown in Figure 13-2.
Figure 13-2: Changing the cursor's iconThis is accomplished with the propertycursor.The default value,auto, simply means that the user agent should determine the cursor icon that is most appropriate for the current context. This is not the same asdefault, which forces the icon to be the operating system's default cursor. The default cursor is usually an arrow, but it does not have to be; it depends on the current computing environment.Section 13.2.1.1: Pointing and selection cursors
The valuepointerchanges the cursor icon to be the same as when the user moves the cursor over a hyperlink. You can even describe this behavior for HTML documents:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Outlines
- InhaltsvorschauCSS2 introduces one last major piece of user-interface styling: outlines. An outline is sort of like a border, but there are two very important differences. First, outlines do not participate in the flow of the document like borders do, and thus don't trigger document reflow as they appear and disappear. If you give an element a 50-pixel outline, the outline will very likely overlap other elements. Second, outlines can be nonrectangular—but don't start leaping for joy just yet. This does not mean that you can create circular outlines. Instead, it means that an outline on an inline element may not act like a border would on that same element. With an outline, a user agent is allowed to "merge" the pieces of the outline to create a single continuous, but nonrectangular, shape. Figure 13-10 shows an example.
Figure 13-10: Outlines can have irregular shapesUser agents are not required to support nonrectangular outlines. They could instead format outlines on inline nonreplaced elements the same way they do borders. A conforming user agent must, however, make sure that outlines do not take up layout space.There is one other basic way in which outlines and borders differ: they aren't the same thing, so they can both exist on the same element. This can lead to some interesting effects, such as that illustrated in Figure 13-11.
Figure 13-11: The coexistence of borders and outlinesThe CSS2 specification states the following: "The outline may be drawn starting just outside the border edge." Note the word may in that sentence. User agents are encouraged to do as the sentence suggests, but it isn't a requirement. A user agent could decide to draw borders inside the inner border edge or at some small distance from the border. As of this writing, all browsers that support outlines draw them just outside the outer border edge, so, thankfully, there is consistency.Outlines are considered to be part of user-interface styling because they are most often used to indicate the current focus. If a user is using keyboard navigation to jump from link to link, then the link that is currently in focus will usually get an outline. In Internet Explorer for Windows, an outline is applied to any link that has been selected by the user ("clicked," if she's using a mouse), and tends to persist even when it isn't wanted. Other browsers apply outlines to text inputs that have the keyboard focus, thus giving a cue to where input will go if the user starts typing.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Summary
- InhaltsvorschauThanks to user interface styles, it's possible for an author to make a document look more like the user's computing environment, especially with a creative use of system color and fonts. By reusing things with which the user is already familiar, a document can seem more familiar and user-friendly from the outset.Another way to make users' lives a little easier is to create style sheets that are targeted at media other than their monitors. This would include styles intended specifically for printing, aural (spoken) access of a web page, and even for a projection-screen environment. We'll cover all of those in the next chapter.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Chapter 14: Non-Screen Media
- InhaltsvorschauNot everyone who accesses the Web can see the effects we've discussed in this book. Some 1.1 million people in the United States are blind, and they have a very different experience of the Web than sighted persons.Fortunately, CSS is not silent on the matter of non-visual access. CSS2 included the ability to apply styles in nonlo-screen media. While most of the Web's evolution has taken place on monitors—that is to say, in a visual medium—CSS2 can be used in non-visual media, assuming that the user agent has proper support.The advantages of designing documents that are at once visually and non-visually usable should not be dismissed. If you can take one document and use different, medium-specific style sheets to restyle it for screen, print, and aural rendering, you can save yourself a whole lot of trouble. For example, you wouldn't need to link to "printer-friendly" versions of a page. Instead of creating totally different markup structures, one for screen and another for print, you can make your site more efficient by reusing the same document.For that matter, it's possible to take a single HTML document that contains the outline of a slideshow and style it for easy reading on a screen, for clean and readable printouts, as a slideshow, and in a manner that a screen reader can translate. In the course of this chapter, we'll look at ways to do the latter three (since the rest of the book concerns itself with screen presentation).You can restrict any kind of style sheet to a specific medium, thanks to the mechanisms defined in HTML and CSS. For HTML-based style sheets, you can impose medium restrictions through the
mediaattribute. This works the same for both thelinkandstyleelements:<link rel="stylesheet" type="text/css" media="print" href="article-print.css"> <style type="text/css" media="projection"> body {font-family: sans-serif;} </style>Themediaattribute can accept a single medium value or a comma-separated list of values. Thus, to link in a style sheet that should be used in only the screen and projection media, you would write:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Designating Medium-Specific Style Sheets
- InhaltsvorschauYou can restrict any kind of style sheet to a specific medium, thanks to the mechanisms defined in HTML and CSS. For HTML-based style sheets, you can impose medium restrictions through the
mediaattribute. This works the same for both thelinkandstyleelements:<link rel="stylesheet" type="text/css" media="print" href="article-print.css"> <style type="text/css" media="projection"> body {font-family: sans-serif;} </style>Themediaattribute can accept a single medium value or a comma-separated list of values. Thus, to link in a style sheet that should be used in only the screen and projection media, you would write:<link rel="stylesheet" type="text/css" media="screen, projection" href="visual.css">
In a style sheet itself, you can also impose medium restrictions on@importrules:@import url(visual.css) screen, projection; @import url(article-print.css) print;
Remember that if you don't add medium information to a style sheet, it will be applied in all media. Therefore, if you want one set of styles to apply only onscreen, and another to apply only in print, then you need to add medium information to both style sheets. For example:<link rel="stylesheet" type="text/css" media="screen" href="article-screen.css"> <link rel="stylesheet" type="text/css" media="print" href="article-print.css">
If you were to remove themediaattribute from the firstlinkelement in the preceding example, the rules found in the style sheet article-screen.css would be applied in all media, including print, projection, handheld, and everything else.CSS2 also defines syntax for@mediablocks, which lets you define styles for multiple media within the same style sheet. Consider this basic example:<style type="text/css"> body {background: white; color: black;} @media screen { body {font-family: sans-serif;} h1 {margin-top: 1em;} } @media print { body {font-family: serif;} h1 {margin-top: 2em; border-bottom: 1px solid silver;} } </style>Here you see that in all media, thebodyelement is given a white background and a black foreground. Then a block of rules is provided for theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Paged Media
- InhaltsvorschauIn CSS terms, a paged medium is any medium where a document's presentation is handled as a series of discrete "pages." This is different from the screen, which is a continuous medium: documents are presented as a single, scrollable "page." An analog example of a continuous medium is a papyrus scroll. Printed material, such as books, magazines, and laser printouts, are all paged media. So are slideshows, where a series of slides is shown one at a time. Each slide is a "page" in CSS terms.Even in the "paperless future," the most commonly encountered paged medium is a printout of some document—a web page, a word-processing document, a spreadsheet, or something else that has been committed to the thin wafers of a dead tree. Authors can do a number of things to make printouts of their documents more pleasing for the user, from affecting page breaking to creating styles meant specifically for print.Note that print styles would also be applied to document display in a "print preview" mode. Thus, it's possible in some circumstances to see print styles on a monitor.
Section 14.2.1.1: Differences between screen and print
Beyond the obvious physical differences, there are a number of stylistic differences between screen and print design. The most basic involves font choices. Most designers will tell you that sans-serif fonts are best suited for screen design, but serif fonts are more readable in print. Thus, you might set up a print style sheet that uses Times instead of Verdana for the text in your document.Another major difference involves font sizing. If you've spent any time at all doing web design, you've probably heard again and again (and again) that points are a horrible choice for font sizing on the Web. This is basically true, especially if you want your text to be consistently sized between browsers and operating systems. However, print design is not web design any more than web design is print design. Using points, or even centimeters or picas, is perfectly OK in print design because printing devices know the physical size of their output area. If a printer has been loaded with 8.5 × 11 paper, then it knows it has a printing area that will fit within the edges of that piece of paper. It also knows how many dots there are in an inch, since it knows how many dots-per-inch (dpi) it's capable of generating. This means that it can cope with physical-world length units like points.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Aural Styles
- InhaltsvorschauUsers who cannot see won't benefit from the visual styling that most of CSS enables. For these users, what matters is not the drop shadows or rounded corners, but the actual textual content of the page—which must be rendered audibly if they are to understand it. The blind are not the only user demographic that can benefit from aural rendering of web content. A user agent embedded in a car, for example, might use aural styles to enliven the reading of web content such as driving directions, or even the driver's email.To meet the needs of these users, CSS2 introduced a section describing aural styles. As of this writing, there are two user agents that support, at least to some degree, aural styles: Emacspeak and Fonix SpeakThis. In spite of this, CSS2.1 effectively deprecates the media type
auraland all of the properties associated with it. The current specification includes a note to the effect that future versions of CSS are likely to use the media typespeechto represent spoken renderings of documents, but it does not provide any details.Due to this odd confluence of emerging implementation and deprecation, we will only briefly look at the properties ofauralstyle sheets.At the most basic level, you must determine whether a given element's content should be rendered aurally at all. Inauralstyle sheets, this is handled with the propertyspeak.The default value,normal, is used to indicate that an element's content should be spoken. If an element's content should not be spoken for some reason, the valuenoneis used. Even though an element's aural rendering may be suppressed usingEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Summary
- InhaltsvorschauAlthough the first stage of the Web's development was primarily visual in nature, the need to provide web content in other media led to the introduction of medium-specific styling in CSS. The ability to take the same document and customize its presentation in a manner best suited to different output media is deeply powerful. Although its most common application is to create "printer-friendly" styles for documents, we've also seen how projection styles can be used to create slideshows with Opera.While aural styles would be very useful for blind users, there are only two programs as of this writing that support even a fragment of this portion of CSS, and the media type
auraldefined in CSS2.x will not be carried forward to future versions of CSS. Instead, the media typespeechhas been set aside for future work in auditory rendering of documents.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Appendix A: Property Reference
- Inhaltsvorschau
Section A.1: Visual Media
Section A.2: Tables
Section A.3: Paged Media
Section A.4: Dropped from CSS2.1
Section A.5: Visual Styles
Section A.6: Paged Media
Section A.7: Aural Styles
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Visual Media
- InhaltsvorschauThis is a shorthand method to express all of the individual background properties within a single declaration. Use of this property is generally encouraged over the individual properties, as it has a slightly better support profile in older browsers and doesn't take as long to type.
- Values:
- [ <background-color> || <background-image> || <background-repeat> || <background-attachment> || <background-position> ] |
inherit - Initial value:
- Refer to individual properties
- Applies to:
- All elements
- Inherited:
- No
- Percentages:
- Values are allowed for <background-position>
- Computed value:
- See individual properties
This property defines whether the background image scrolls along with the element when the document is scrolled. This can be used to create "aligned" backgrounds; see Chapter 9 for more details.- Values:
scroll|fixed|inherit- Initial value:
scroll- Applies to:
- All elements
- Inherited:
- No
- Computed value:
- As specified
This sets a solid color for the background of the element. This color fills the content, padding, and border areas of the element, extending to the outer edge of the element's border. Borders that have transparent sections, such as dashed borders, will show the background color through the transparent sections.- Values:
- <color> |
transparent|inherit - Initial value:
transparent- Applies to:
- All elements
- Inherited:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Tables
- InhaltsvorschauThis property defines the layout model used in laying out the borders in a table—i.e., those applied to cells, rows, and so forth. Although the property applies only to tables, it is inherited by all the elements within the table.
- Values:
collapse|separate|inherit- Initial value:
separate- Applies to:
- Elements with the
displayvaluetableorinline-table - Inherited:
- Yes
- Computed value:
- As specified
- Note:
- In CSS2, the default value was
collapse
This specifies the distance between cell borders in the separated borders model. The first of the two length values is the horizontal separation, and the second is the vertical. This property is ignored unlessborder-collapseis set toseparate. Although the property only applies to tables, it is inherited by all of the elements within the table.- Values:
- <length> <length>? |
inherit - Initial value:
0- Applies to:
- Elements with the
displayvaluetableorinline-table - Inherited:
- Yes
- Computed value:
- Two absolute lengths
- Note:
- This property is ignored unless
border-collapsevalue isseparate
This specifies the placement of a table caption with respect to the table box. The caption is rendered as though it were a block-level element placed just before (or after) the table.- Values:
top|bottom- Initial value:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Paged Media
- InhaltsvorschauThis specifies the minimum number of text lines within the element that can be left at the bottom of a page. This can affect the placement of page breaks within the element.
- Values:
- <integer> |
inherit - Initial value:
2- Applies to:
- Block-level elements
- Inherited:
- Yes
- Computed value:
- As specified
This declares whether page breaks should be placed after an element. While it is possible to force breaks withalways, it is not possible to guarantee prevention; the best an author can do is ask the user agent toavoidinserting a page break if possible.- Values:
auto|always|avoid|left|right|inherit- Initial value:
auto- Applies to:
- Nonfloated block-level elements with a
positionvalue ofrelativeorstatic - Inherited:
- No
- Computed value:
- As specified
Declares whether page breaks should be placed before an element. While it is possible to force breaks withalways, it is not possible to guarantee prevention; the best an author can do is ask the user agent toavoidinserting a page break if possible.- Values:
auto|always|avoid|left|right|inherit- Initial value:
auto- Applies to:
- Nonfloated block-level elements with a
positionvalue ofrelativeorstatic - Inherited:
- No
- Computed value:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Dropped from CSS2.1
- InhaltsvorschauThe following properties appeared in CSS2 but were dropped from CSS2.1 due to a lack of widespread support. They do not have computed value information since computed values were first explicitly defined in CSS2.1.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Visual Styles
- InhaltsvorschauThe aim of this property is to allow authors to trigger font scaling such that substitute fonts will not look too different from the font the author intended, even if the substitute font has a different x-height. Note that this property does not appear in CSS2.1.
- Values:
- <number> |
none|inherit - Initial value:
none- Applies to:
- All elements
- Inherited:
- Yes
With this property, the character glyphs in a given font can be made wider or narrower, ideally by selected condensed or expanded faces from the font's family. Note that this property does not appear in CSS2.1.- Values:
normal|wider|narrower|ultra-condensed|extra-condensed|condensed|semi-condensed|semi-expanded|expanded|extra-expanded|ultra-expanded|inherit- Initial value:
normal- Applies to:
- All elements
- Inherited:
- Yes
This property specifies the distance between the nearest border edge of a marker box and its associated element box.- Values:
- <length> |
auto|inherit - Initial value:
auto- Applies to:
- Elements with a
displayvalue ofmarker - Inherited:
- No
- Note:
- This property is obsolete as of CSS2.1 and will likely not reappear in CSS3, and the same is true for the
displayvalue ofmarker; as of this writing, it appears that other mechanisms will be used to achieve these effects
This permits the assignment of one or more "shadows" to the text in an element. The first two length values in a shadow definition set horizontal and vertical offsets, respectively, from the element's text. The third length defines a blurring radius. Note that this property does not appear in CSS2.1.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Paged Media
- InhaltsvorschauThis property defines whether "cross marks" (otherwise known as register marks or registration marks) should be placed outside the content area but within the printable area of the canvas. The exact placement and rendering of the marks is not defined. Note that this value does not appear in CSS2.1.
- Values:
- [
crop||cross] |none|inherit - Initial value:
none- Applies to:
- Page context
- Inherited:
- N/A
This property, in conjunction withsize, specifies a particular page type to be used in the printing of an element. Note that this property does not appear in CSS2.1.- Values:
- <identifier> |
inherit - Initial value:
auto- Applies to:
- Block-level elements
- Inherited:
- Yes
With this property, authors can declare the size and orientation of the page box used in the printing of an element. It can be used in conjunction withpage, although this is not always necessary. Note that this property does not appear in CSS2.1.- Values:
- <length>{1,2} |
auto|portrait|landscape|inherit - Initial value:
auto- Applies to:
- The page area
- Inherited:
- No
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Aural Styles
- InhaltsvorschauThis property sets the angle along the horizontal plane (otherwise known as the horizon) from which a sound should seem to emanate. This is used in conjunction with
elevationto place the sound at a point on a hypothetical sphere with the user at its center.- Values:
- <angle> | [[
left-side|far-left|left|center-left|center|center-right|right|far-right|right-side] ||behind] |leftwards|rightwards|inherit - Initial value:
center- Applies to:
- All elements
- Inherited:
- Yes
- Computed value:
- Normalized angle
This is a shorthand property that allows an author to define cues that precede and follow the audio rendering of an element's content. A "cue" is something like an auditory icon.- Values:
- [ <cue-before> || <cue-after> ] |
inherit - Initial value:
none- Applies to:
- All elements
- Inherited:
- No
- Computed value:
- See individual properties (
cue-before, etc.)
This property allows an author to define a cue that follows the audio rendering of an element's content.- Values:
- <uri> |
none|inherit - Initial value:
none- Applies to:
- All elements
- Inherited:
- No
- Computed value:
- For <uri> values, the absolute URI; otherwise,
none
This property allows an author to define a cue that precedes the audio rendering of an element's content.- Values:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Appendix B: Selector, Pseudo-Class, and Pseudo-Element Reference
- Inhaltsvorschau
Section B.1: Selectors
Section B.2: Pseudo-Classes and Pseudo-Elements
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Selectors
- InhaltsvorschauThis selector matches any element name in the document's language. If a rule does not have an explicit selector, then the universal selector is inferred.Pattern:
*Examples:* {color: red;} div * p {color: blue;}This selector matches the name of an element in the document's language. Every instance of the element name is matched. (CSS1 referred to these as element selectors.)Pattern:element1Examples:body {background: #FFF;} p {font-size: 1em;}This allows the author to select an element based on its status as a descendant of another element. The matched element can be a child, grandchild, great-grandchild, etc., of the ancestor element. (CSS1 referred to these as contextual selectors.)Pattern:element1 element2Examples:body h1 {font-size: 200%;} table tr td div ul li {color: purple;}This type of selector is used to match an element based on its status as a child of another element. This is more restrictive than a descendant element, since only a child will be matched.Pattern:element1 > element2Examples:div > p {color: cyan;} ul > li {font-weight: bold;}This allows the author to select an element that is the following adjacent sibling of another element. Any text between the two elements is ignored; only elements and their positions in the document tree are considered.Pattern:element1 + element2Examples:table + p {margin-top: 2.5em;} h1 + * {margin-top: 0;}In languages that permit it, such as HTML, SVG, and MathML, a class selector using "dot notation" can be used to select elements that have a class containing a specific value or values. The name of the class value must immediately follow the dot. Multiple class values can be "chained" together. If no element name precedes the dot, the selector matches all elements containing that class value.Patterns:element1.classname element1.classname1.classname2Examples:p.urgent {color: red;} a.external {font-style: italic;} .example {background: olive;}In languages that permit it, such as HTML, an ID selector using "hash notation" can be used to select elements that have an ID containing a specific value or values. The name of the ID value must immediately follow the octothorpe (Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Pseudo-Classes and Pseudo-Elements
- InhaltsvorschauThis applies to an element during the period in which it is activated. The most common example of this is clicking on a hyperlink in an HTML document: during the time that the mouse button is held down, the link is active. There are other ways to activate elements, and other elements can in theory be activated, although CSS doesn't define this.Type: Pseudo-classApplies to: An element that is being activatedExamples:
a:active {color: red;} *:active {background: blue;}This allows the author to insert generated content at the end of an element's content. By default, the pseudo-element is inline, but this can be changed using the propertydisplay.Type: Pseudo-elementGenerates: A pseudo-element containing generated content placed after the content in the elementExamples:a.external:after {content: " " url(/icons/globe.gif);} p:after {content: " | ";}This allows the author to insert generated content at the beginning of an element's content. By default, the pseudo-element is inline, but this can be changed using the propertydisplay.Type: Pseudo-elementGenerates: A pseudo-element containing generated content placed before the content in the elementExamples:a[href]:before {content: "[LINK] ";} p:before {content: attr(class);}With this pseudo-class, an element is matched only when it is the first child of another element. For example,p:first-childwill select anypelement that is the first child of some other element. It does not, as is commonly assumed, select whatever element is the first child of a paragraph; for that, an author would writep > *:first-child.Type: Pseudo-classApplies to: Any element that is the first child of another elementExamples:body *:first-child {font-weight: bold;} p:first-child {font-size: 125%;}This is used to style the first letter of an element. Any leading punctuation should be styled along with the first letter. Some languages have letter combinations that should be treated as a single character, and a user agent may apply the first-letter style to both. Prior to CSS2.1,:first-lettercould be attached only to block-level elements. CSS2.1 expands its scope to include all elements. There is a limited set of properties that can apply to a first letter.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Appendix C: Sample HTML 4 Style Sheet
- InhaltsvorschauThe following style sheet is adapted from Appendix D of the CSS2.1 specification. There are two important things to note. The first is that while CSS2.1 says that "developers are encouraged to use [this] as a default style sheet in their implementations," this isn't always possible. For example, there is a rule that states:
ol, ul, dir, menu, dd {margin-left: 40px;}This describes the legacy indenting of lists to a distance of 40 pixels, and it uses a left margin to do it. However, some browsers have used a 40-pixel left padding instead of a margin, believing this to be a better solution. (See Chapter 12 for details.) Therefore, you cannot rely on this as the exact default style sheet for any given user agent. It is provided more for illustrative purposes and as a learning tool.The second thing to note is that not all HTML elements are fully described in this style sheet because CSS is not yet detailed enough to completely and accurately describe them. The classic examples are form elements, such as submit buttons, which are replaced elements but have their own special formatting needs. Submit buttons are replaced elements, and thus the bottom edge of their box should align with the baseline. Authors, however, are likely to expect the text inside the button to align with the baseline of other text in the same line. This is a reasonable expectation, but CSS does not (as of this writing) have the ability to describe such behavior; therefore, all that is said about such elements is the following rule:button, textarea, input, object, select, img { display:inline-block;}The rest of the formatting of such elements is left to the user agent.With these caveats in mind, here is the style sheet (with some slight reformatting) found in the CSS2 specification. Any changes other than reformatting are noted in comments.address, blockquote, body, dd, div, dl, dt, fieldset, form, frame, frameset, h1, h2, h3, h4, h5, h6, noframes, ol, p, ul, center, dir, hr, menu, pre { display: block;} li {display: list-item;} head {display: none;} table {display: table;} tr {display: table-row;} thead {display: table-header-group;} tbody {display: table-row-group;} tfoot {display: table-footer-group;} col {display: table-column;} colgroup {display: table-column-group;} td, th {display: table-cell;} caption {display: table-caption;} th {font-weight: bolder; text-align: center;} caption {text-align: center;} body {padding: 8px; line-height: 1.12em;} h1 {font-size: 2em; margin: .67em 0;} h2 {font-size: 1.5em; margin: .75em 0;} h3 {font-size: 1.17em; margin: .83em 0;} h4, p, blockquote, ul, fieldset, form, ol, dl, dir, menu { margin: 1.12em 0;} h5 {font-size: .83em; margin: 1.5em 0;} h6 {font-size: .75em; margin: 1.67em 0;} h1, h2, h3, h4, h5, h6, b, strong { font-weight: bolder;} blockquote {margin-left: 40px; margin-right: 40px;} i, cite, em, var, address { font-style: italic;} pre, tt, code, kbd, samp { font-family: monospace;} pre {white-space: pre;} button, textarea, input, object, select, img { display:inline-block;} big {font-size: 1.17em;} small, sub, sup {font-size: .83em;} sub {vertical-align: sub;} sup {vertical-align: super;} s, strike, del {text-decoration: line-through;} hr {border: 1px inset;} ol, ul, dir, menu, dd { margin-left: 40px;} ol {list-style-type: decimal;} ol ul, ul ol, ul ul, ol ol { margin-top: 0; margin-bottom: 0;} u, ins {text-decoration: underline;} br:before {content: "\A";} center {text-align: center;} abbr, acronym {font-variant: small-caps; letter-spacing: 0.1em;} :link,:visited {text-decoration: underline;} :focus {outline: thin dotted invert;} /* Begin bidirectionality settings (do not change) */ BDO[DIR="ltr"] {direction: ltr; unicode-bidi: bidi-override;} BDO[DIR="rtl"] {direction: rtl; unicode-bidi: bidi-override;} *[DIR="ltr"] {direction: ltr; unicode-bidi: embed;} *[DIR="rtl"] {direction: rtl; unicode-bidi: embed;} @media print { h1 {page-break-before: always;} h1, h2, h3, h4, h5, h6 { page-break-after: avoid;} ul, ol, dl {page-break-before: avoid;} } @media aural { /* changed from 'speech' which was not defined in CSS2 */ h1, h2, h3, h4, h5, h6 { voice-family: paul, male; stress: 20; richness: 90;} h1 {pitch: x-low; pitch-range: 90;} h2 {pitch: x-low; pitch-range: 80;} h3 {pitch: low; pitch-range: 70;} h4 {pitch: medium; pitch-range: 60;} h5 {pitch: medium; pitch-range: 50;} h6 {pitch: medium; pitch-range: 40;} li, dt, dd {pitch: medium; richness: 60;} dt {stress: 80;} pre, code, tt {pitch: medium; pitch-range: 0; stress: 0; richness: 80;} em {pitch: medium; pitch-range: 60; stress: 60; richness: 50;} strong {pitch: medium; pitch-range: 60; stress: 90; richness: 90;} dfn {pitch: high; pitch-range: 60; stress: 60;} s, strike {richness: 0;} i {pitch: medium; pitch-range: 60; stress: 60; richness: 50;} b {pitch: medium; pitch-range: 60; stress: 90; richness: 90;} u {richness: 0;} a:link {voice-family: harry, male;} a:visited {voice-family: betty, female;} a:active {voice-family: betty, female; pitch-range: 80; pitch: x-high;} }Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Zurück zu CSS: The Definitive Guide
