How Inheritance Works in CSS
Figure 3.1. A simple HTML inheritance tree
Each element in an HTML document (with the exception of the root html ele-
ment) has a parent element. This is the element that directly precedes it in the
tree. In Figure 3.1, p
1
’s parent is the body element. Likewise, p
1
is said to be a
child of the body element.
Most elements in an HTML document will be descendants of more than one
element. For example, in Figure 3.1, the paragraph element p
1
is a descendant of
the body and html elements. Similarly, the paragraph element p
2
is a descendant
of the div, body, and html elements. This notion of element hierarchy is important
for two reasons:
❑
The proper use of some of the CSS selectors you’ll work with will depend on
your understanding of the document hierarchy. There is, for example, an im-
portant difference between a descendant selector and a parent-child selector.
These are explained in detail in the section called “Selectors and the Structure
of CSS Rules”, later in this chapter.
❑
If you don’t supply a specific value for an element’s property, in many cases,
that element will take the value assigned to its parent. Consider the example
document shown in Figure 3.1. If the body element had a declaration for the
font-family property and p
1
did not, p
1
would inherit the body element’s
font-family. In contrast, setting the width property of an element will not
directly affect the width of its child elements. font-family is an inherited
property; width is not.
43
Licensed to siowchen@darke.biz
Chapter 3: Digging Below the Surface
The properties that are inherited—and those that are not—are indicated in
Appendix C. However, you can set any property to the special value inherit,
which will cause it to inherit the value assigned to its parent element.
This inheritance issue can become tricky when you’re dealing with fairly
complex documents. It’s particularly important when you’re starting with a
site that’s been defined using the traditional table layout approach, in which
style information is embedded in HTML tags. When a style sheet seems not
to function properly, you’ll often find that the problem lies in one of those
embedded styles from which another element is inheriting a value.
Selectors and the Structure of CSS Rules
In Chapter 1 we learned that every CSS style rule consists of two parts: a selector,
which defines the type(s) of HTML element(s) to which the style rule applies;
and a series of declarations, consisting of properties and values, that define the
style.
So far, we’ve seen only simplistic selectors. Typically, they’ve contained only one
element:
h1 {
font-size: 120%;
text-transform: capitalize;
}
We’ve encountered one or two instances where a single rule is designed to apply
to more than one kind of HTML element:
h1, h2, h3 {
font-size: 120%;
text-transform: capitalize;
}
In this section, we’ll take a look at all the different kinds of selectors that are
available to you in CSS.
Universal Selector
The universal selector matches every element in the document. It has very little
practical value by itself, but the universal selector can come in handy in specific
44
Licensed to siowchen@darke.biz
Element Type Selector
situations involving, for example, attribute selectors, which I’ll explain later in
this section.
In this example, all elements in the page are given a text color of red:
* {
color: red;
}
Element Type Selector
The element type selector is the most common selector. It specifies one HTML
element type with no qualifiers. In the absence of other style rules that might
apply to the element type provided in the selector, this rule applies to all such
elements on the page.
In this example, we specify the text and background color of all hyperlinks in the
current document. They will appear as white text on a green background.
a {
color: white;
background-color: green;
}
Class Selector
To apply a style rule to a potentially arbitrary group of elements in a web page,
you’ll need to define a class in the style sheet, then identify the HTML elements
that belong to that class using the class attribute.
To define a class in a style sheet, you must precede the class name with a period.
No space is permitted between the period and the name of the class.
The following style sheet entry defines a class named special.
.special {
font-family: Verdana, Helvetica, Arial, sans-serif;
}
Then, we add class="special" to the elements that we want to adopt this style.
<h1 class="special">A Special Heading</h1>
<p class="special">This is a special paragraph.</p>
45
Licensed to siowchen@darke.biz
Chapter 3: Digging Below the Surface
You can write your class so that it applies only to a particular type of element.
In the following example, we create the same special class, but this time it applies
only to paragraph elements.
p.special {
font-family: Verdana, Helvetica, Arial, sans-serif;
}
If you define an element-specific class such as the p.special example above,
then associate that class (in this case, special) with an element of any other
type, the style rule simply does not apply to that element.
An HTML element can belong to multiple classes: simply list those classes (sep-
arated by spaces) in the class attribute:
<p class="special exciting">Paragraph! Of! Stuff!</p>
ID Selector
An ID selector lets you target a single HTML element within a page. Like a class
selector, an ID selector must be defined in the style sheet and included explicitly
in the HTML tag. Use the # symbol to identify an ID selector in the style sheet,
2
and the id attribute to give an element an ID. IDs must be unique within a
document; no two HTML elements in a single document should have the same
ID.
This style sheet rule defines a rule for an element with the ID unique:
#unique {
font-size: 70%;
}
The code below uses the HTML id attribute to indicate the element that will be
affected by the rule above:
<h4 id="unique">This will be a very tiny headline</h4>
For example, if you had five <div class="sidebar"> items on your page, but
you wanted to style differently the one responsible for displaying your site’s
search box, you could do so like this:
2
Optionally, you can confine the ID’s use to an element of a specific type by preceding the # with
the HTML element’s tag name (e.g. div#searchbox). But, since you can have only one element
with the specific ID within a document, it seems silly to confine it to a specific element type.
46
Licensed to siowchen@darke.biz
Pseudo-element Selector
div.sidebar {
border: 1px solid black;
background-color: yellow;
}
#searchbox {
background-color: orange;
}
The search box would then appear in your HTML as shown here:
<div id="searchbox" class="sidebar">
<! HTML for search form >
</div>
Now, since the div has id="searchbox" and class="sidebar" attributes, all
the sidebar declarations will be applied to the search box, but it will take its
background-color from the #searchbox rule. The guidelines for cascading
overlapping rules (discussed in Chapter 9), in combination with the ID selector,
let you avoid having to redefine all the sidebar properties in a special searchbox
class.
However, you could just as easily define a class and apply it to the exceptional
element (the search box, in this example). This approach is more flexible, although
perhaps not as efficient in terms of code space. For example, imagine you’ve
identified a class or other rule that applies to all level-three headings except one,
and you’ve used an ID selector for the exception. What do you do when a redesign
or content change requires one more such exception? The ID selector solution
breaks down immediately in that situation.
Pseudo-element Selector
This and all the remaining selectors in this section require a browser that supports
the CSS 2 specification, such as Firefox, Safari, Opera, or Internet Explorer 7.
Some features, such as the :hover pseudo-class, are supported by some older
browsers, but their implementations are not complete.
Pseudo-element selectors and pseudo-class selectors are unique among the CSS
selectors in that they have no equivalent HTML tag or attribute. That’s why they
use the prefix “pseudo” (meaning “false”).
So far, the CSS specification has defined only three pseudo-elements: first-
letter
, first-line, and first-child. While the first two of these phrases
mean something to us humans, it’s ultimately up to each browser to interpret
47
Licensed to siowchen@darke.biz
Chapter 3: Digging Below the Surface
them when rendering HTML pages that use these pseudo-elements. For example,
does first-line mean “first sentence,” or does it mean the first physical line
that’s displayed—a value that changes as the user resizes the browser? The first-
child
pseudo-element, on the other hand, is not browser-dependent. It refers to
the first descendant of the element to which it is applied, in accordance with the
HTML document hierarchy described in the section called “How Inheritance
Works in CSS”.
To define a pseudo-element selector for a style rule, precede the pseudo-element
name with a colon. Here’s an example:
p:first-letter {
font-family: serif;
font-size: 500%;
float: left;
color: gray;
}
This creates a drop-caps effect for the first letter in every paragraph on the page,
as shown in Figure 3.2. The first letter in each paragraph will be five times larger
than the usual type used in paragraphs. The float style property, which we discuss
in Chapter 8, ensures the remaining text in the paragraph wraps around the en-
larged drop-cap correctly.
Figure 3.2. Creating a drop-caps effect using the first-letter
pseudo-element
Pseudo-class Selector
A pseudo-class selector is exactly like the pseudo-element selector, with one
exception. A pseudo-class selector applies to a whole element, but only under
certain conditions.
The current release of CSS 2 defines the following pseudo-classes:
48
Licensed to siowchen@darke.biz
Pseudo-class Selector
❑
hover
❑
active
❑
focus
❑
link
❑
visited
❑
lang
A style sheet, then, can define style rules for these pseudo-classes as shown in
the example below. You may remember that we’ve already seen a rule that uses
the hover pseudo-class.
a:hover {
color: green;
}
All anchor tags will change color when the user mouses over them. As you can
see, this means the pseudo-class selector comes into play only when the user in-
teracts with the affected element.
The lang pseudo-class
3
refers to the setting of the lang attribute in an HTML
element. For example, you could use the lang attribute shown below to define
a paragraph in a document as being written in German:
<p lang="de">Deutsche Grammophon</p>
If you wanted, for example, to change the font family associated with all elements
in the document that were written in German, you could write a style rule like
this:
:lang(de) {
font-family: spezialitat;
}
lang vs language
Be careful not to confuse this lang attribute with the deprecated language
attribute that used to be used to set the scripting language used in pages.
3
Be aware that browser support for the lang pseudo-class is still very scarce. It’s covered here mainly
for the sake of completeness.
49
Licensed to siowchen@darke.biz
Chapter 3: Digging Below the Surface
Descendant Selector
As we’ve discussed, all HTML elements (except the html element) are descendants
of at least one other HTML element. To apply a CSS style rule to an element
only when it’s a descendant of some other kind of element, we can use a descend-
ant selector.
A descendant selector, such as the one shown in the following style rule, restricts
the applicability of the rule to elements that are descendants of other elements.
The scope of the descendant selector is determined by reading the rule from right
to left. Spaces separate the element types.
li em {
color: green;
}
The style rule identifies that a color of green will be applied to any text contained
in an em, or emphasis, element only when the emphasized text is a descendant of
a list item.
In the fragment below, the first em element will be displayed in green characters;
the second will not, as it doesn’t appear within a list item.
<ul>
<li>Item one</li>
<li>Item <em>two</em></li>
</ul>
<p>An <em>italicized</em> word.</p>
It’s important to note that the descendant relationship need not be an immediate
parent-child connection. Take this markup, for example:
<div class="sidebar">
<p>If you have any questions, <a href="contact.html">please call
our office during business hours</a>.</p>
</div>
The following style rule would apply to the anchor element even though it focuses
explicitly on a elements that are descendants of div elements. This is because,
in this case, the a element is the child of a paragraph that’s contained in a div
element.
50
Licensed to siowchen@darke.biz
Parent-child Selector
div a {
font-style: italic;
}
Parent-child Selector
A parent-child selector causes a style rule to apply to element patterns that
match a specific sequence of parent and child elements. It is a special case of the
descendant selector that we discussed above. The key difference between the two
is that the pair of elements in a parent-child selector must be related directly to
one another in a strict inheritance sequence.
A parent-child relationship is specified in a selector with the “greater than” sign
(>).
Below is an example of a parent-child relationship.
body > p {
font-weight: bold;
}
In the example below, this rule will only affect para2, as para1 and para3 are
not direct descendants of the body element.
<body>
<div class="sidebar">
<p id="para1">This is the sidebar.</p>
</div>
<p id="para2">Welcome to the web site! Here's a list:</p>
<ul>
<li>
<p id="para3">This is the first paragraph in the list. It's
also the last.</p>
</li>
</ul>
</body>
As of this writing, Internet Explorer for Windows (up to and including version
6) distinguishes itself by being the only major browser that does not support
parent-child selectors. Because of this, careful use of descendant selectors is far
more common, and the parent-child selector is often abused to specifically create
styles that do not apply to Internet Explorer for Windows.
51
Licensed to siowchen@darke.biz
Chapter 3: Digging Below the Surface
Adjacent Selector
Adjacency is not related to inheritance. Adjacency refers to the sequence in which
elements appear in an HTML document. As it happens, adjacent elements are
always siblings, but it’s their placement in the document, rather than their inher-
itance relationship, that is the focus of this selector. This point is demonstrated
in the HTML fragment below:
<h1>This is important stuff!</h1>
<h2>First important item</h2>
<h2>Second important item</h2>
The first h2 heading is adjacent to the h1 heading, but the second h2 heading is
not adjacent to the h1 heading.
The adjacent selector uses the + sign as its connector, as shown here:
h1 + h2 {
margin-top: 11px;
}
This style rule would put 11 extra pixels of space between the bottom of an h1
heading and an h2 heading that followed it immediately. It’s important to recog-
nize that an h2 heading that follows a paragraph under an h1 heading would not
be affected.
As of this writing, Internet Explorer for Windows (up to and including version
6) remains the only major browser that does not support adjacent selectors, al-
though support is planned for Internet Explorer version 7. Because of this, the
adjacent selector has not yet found widespread use in practical web design.
Attribute Selectors
The group of selectors I’m lumping together as attribute selectors are among
the most interesting of all the CSS selectors, because they almost feel like pro-
gramming techniques. Each attribute selector declares that the rule with which
it is associated is applied only to elements that have a specific attribute defined,
or have that attribute defined with a specific value.
There are four levels of attribute matching:
[attribute]
matches if the attribute attribute is defined at all for
the element(s)
52
Licensed to siowchen@darke.biz
Không có nhận xét nào:
Đăng nhận xét