3.4. Selectors and Structure of CSS Rules

Recall from Chapter 1, 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 property declarations that define the style.

So far, we've seen only simplistic selectors. Typically, they've contained only one element:

h1 {
  font-size: 18px;
  text-transform: capitalize;
}

We have 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: 18px;
  text-transform: capitalize;
}

These are the most basic selectors in CSS. There are many others. Table 3-1 summarizes all the selector types available in CSS, roughly from simplest to most complex. The remainder of this section describes each type of selector in detail, in the order in which they appear in Table 3-1. Selector types that are defined for the first time in the CSS2 specification or that have changed between CSS1 and CSS2 are marked with "(CSS2)."

Table 3-1. Types of CSS Selectors
Selector TypeUse or MeaningExample(s)
universal selector (CSS2)Apply rule to all elements in document.
*(no selector)
element typeApply rule to all HTML elements of the selector's type.
h1 p
class selectorApply rule to all HTML elements of the type preceding the period (or all, if none is specified) whose definition makes them part of the class following the period of the selector.
.articletitleh1.important
ID selectorApply rule to only one element in the entire document: the one whose id attribute matches the string following the pound sign (hash mark) in the selector.
#special3p#special52
pseudo-element selector (CSS2)Apply rule to occurrences of the pseudo-element.
p:first-letterp:first-lineh1:first-child
pseudo-class selector (CSS2)Apply rule to occurrences of the pseudo-class, whose appearance may change as the user interacts with the page.
a:hovera:activea:focusa:linka:visitedbody:lang(d)
descendant selectorApply rule to all elements of the type listed last in the selector, but only when they occur within the other element type(s) given.
p emp.wide em
parent-child selector (CSS2)Apply rule to all elements of type specified to the right of the ">" that are children of the elements to the left of the ">" (stricter form of the descendant selector).body > p
adjacent selector (CSS2)Apply rule to all elements of type specified to the right of the "+" that are physically adjacent (in the HTML code, not necessarily on the visible page) to elements of the type to the left of the "+".
h1+h2p+h3
attribute selector (CSS2)Apply rule to all elements with attributes matching the profile specified in square brackets.
p[align]input[type="text"]img[alt~="none"]body[lang|="en"]

3.4.1. Universal Selector

The universal selector has no real practical value by itself. A style rule with no selector applies to all elements of all types on a Web page, so the asterisk is superfluous.

However, the universal selector can come in handy in specific situations involving, for example, attribute selectors, which I explain later in this section.

In this example, all elements in the page are given a text color of red:

* {
  color: red;
}

3.4.2. Element Type Selector

The single element selector is the most common selector. It specifies one HTML element type with no qualifiers or enhancements.

In the absence of other style rules applying 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 colors (black and white, respectively) for the document by assigning these properties to the body element:

body {
  color: black;
  background-color: white;
}

3.4.3. 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, and then identify through their HTML tags the elements that belong to that class.

Defining a class in a style sheet requires that you 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. Because there's no HTML element name associated with the class, any type of element on a page using this style sheet can be identified with the class, as you'll see in a moment.

.special {
  font-family: verdana, arial, sans-serif;
}

If you want to include only elements of a particular type in your class, you can use the more specific selector shown here:

p.special {
  font-family: verdana, arial, sans-serif;
}

The above style rule would apply only to paragraph elements that were identified as being members of the class called special.

Within the HTML markup, you can indicate that an element belongs to a class by using the element's class attribute :

<p class="special">Paragraph of stuff.</p>

An HTML element can belong to multiple classes if you wish, simply by listing the classes (separated by spaces) in the class attribute:

<p class="special exciting">Paragraph! Of! Stuff!</p>

If you define an element-specific class such as the p.special example above, and 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.

3.4.4. ID Selector

The ID selector permits you to identify single instances of HTML elements where you wish to override the style properties set in, for example, a class style rule. Like a class selector, an ID selector requires definition in the style sheet and explicit inclusion in the HTML tag. Use the "#" symbol to identify an ID selector[1]. IDs must be unique within a document; no two HTML tags in a single document should have the same ID.

[1] You can optionally 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, as you can have only one element with the specific ID in your document, it seems silly to confine it to a specific element type.

This style sheet rule defines a rule for an element with the ID unique:

#unique {
  font-size: 10px;
}

The code below shows how to indicate the element to be affected by the above rule using the HTML id attribute :

<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:

div.sidebar
{
  …
}
#searchbox
{
  …
}

Now, if both of these rules define a background-color property, and your search box tag was <div id="searchbox" class="sidebar">, then the search box would get all the sidebar properties assigned to it, but it would 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 is more flexible, although perhaps not as efficient in terms of code space. For example, after you've identified a class or other rule that applies to all level three headings except one, and if you've used an ID selector for the exception, what do you do when a redesign or content change requires even one more such exception? The ID selector solution breaks down immediately in that situation.

It appears from my testing that not all of the newer browsers enforce the rule that the ID be unique in the document. Instead, they apply the ID rule to all elements in the document that carry the ID. That makes the ID essentially equivalent to the class selector. This is clearly not what the CSS specification had in mind, but it is how many of the browsers I've tested behave.

3.4.5. Pseudo-Element Selector

This and all the remaining selectors in this section require a browser that supports the CSS2 specification.

The pseudo-element 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 them when rendering HTML pages using these pseudo-elements. For example, does first-line mean "first sentence" or does it mean first physical line 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 Section 3.3.

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-face: Gothic, serif;
  font-size: 250%;
  float: left;
}

This creates a drop-caps effect for the first letter in every paragraph on the page. The first letter in each paragraph will be a Gothic letter 2.5 times larger than the usual type used in paragraphs. The float style property, which we discuss in Chapter 6, ensures the remaining text in the paragraph wraps around the enlarged drop-cap correctly.

3.4.6. Pseudo-Class Selector

The 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 CSS2 defines the following pseudo-classes :

  • :hover

  • :active

  • :focus

  • :link

  • :visited

  • :lang()

A style sheet, then, can define style rules for these pseudo-classes like this:

a:hover {
  color:#ffcc00;
}

All anchor tags will change their color when the user hovers over them with the cursor. As you can see, this means the pseudo-class selector comes into play only when the user interacts with the affected element.

The :lang() pseudo-class[2] refers to the setting of the lang attribute in an HTML element. For example, you can define a paragraph in a document as being written in German, with a tag like this:

[2] Be aware that browser support for the :lang() pseudo-class is still very scarce. It is covered here mainly for the sake of completeness.

<p lang="de">Deutsche Grammophone</p>

If you wanted, for example, to change the font family associated with all elements in the document written in German, you could write a style rule like this:

:lang(de) {
  font-family: spezialitat;
}

Don't confuse this lang attribute with the language attribute that applies to tags related to the scripting language being used in a script or on a page.

3.4.7. Descendant Selector

Recall that 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 that's a descendant of another type of element, use the descendant 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 descendant selector is read from right to left to determine its scope. Spaces separate the element types.

li em {
  font-size: 16px;
  color: green;
}

The style rule describes a 16-pixel-high font size and a color of green to be applied to any text contained in an em element (emphasis) only where the emphasized text is a descendant of a list item.

In the fragment below, the first em element will be displayed in green, 16-pixel characters, while 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. In Figure 3-1, for example, the following style rule would apply to the anchor element (a) even though it explicitly focuses 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.

div a {
  font-style: italic;
}

3.4.8. Parent-Child Selector

The 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 discussed in the preceding section. The key difference between the two is that the pair of elements in a parent-child selector must be directly related to one another in a strict inheritance sequence.

A parent-child relationship is specified in a selector with the "greater-than" sign (>).

The following style rule:

body > p {
  font-weight: bold;
}

will not apply to the p2, p3 or p4 elements in Figure 3-1 because these paragraph elements aren't children of a body element. Even though they are descendants of body, they are not children. Only p1, which is a direct child of the body tag, will be affected by the rule.

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 in its latest version. 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.

3.4.9. Adjacent Selector

Adjacency is unrelated 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 inheritance relationship, that is the focus of this selector. This is demonstrated in this HTML fragment:

<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. The second h2 heading is not adjacent to the h1 heading. Neither h2 heading inherits from 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 an extra 11 pixels of space between the bottom of an h1 heading and an immediately-following h2 heading. It's important to recognize 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 in its latest version. Because of this, the adjacent selector has not yet found widespread use in practical Web design.

3.4.10. 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 programming 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 is defined at all for the element(s)

  • [attribute="setting"] – matches only if the attribute is defined as having the value of setting

  • [attribute~="setting"] – matches only if the attribute is defined with a space-separated list of values, one of which exactly matches "setting"

  • [attribute|="setting"] – matches only if the attribute is defined with a hyphen-separated list of "words" and the first of these words begins with setting

You might, for example, want to apply style properties to all single-line text input boxes (<input type="text" />) in your document. Perhaps you want to set their text and background colors to white and black, respectively. This style rule would have that effect:

input[type="text"] {
  color: white;
  background-color: black;
}

The third variation of the attribute selector described above searches the values assigned to an attribute, to see whether it contains the word you've specified (i.e. a value in a space-separated list).

For example, during the development of a Website, various graphic designers may have inserted temporary placeholder alt text tags, with the idea of returning to them later to finish them. You could call attention to the existence of such tags with a style rule like this:

img[alt~="placeholder"] {
  border: 8px solid red;
}

This selector will find all img tags whose alt attributes contain the word "placeholder" and will put an 8-pixel red border around them. That ought to be hard to miss!

The fourth variation is really useful only when you're dealing with the lang attribute. It enables you to isolate the first portion of the lang attribute, where the human language being used is defined. The other portions of the hyphen-separated value are ignored. It would be pretty rare to use this version, but it comes in handy when the language defined is en-cockney and you're really only interested in whether the language is English.

As you would expect by now, attribute selectors are not supported by Internet Explorer for Windows. As with other advanced selector types, this has prevented widespread adoption of attribute selectors, despite their obvious usefulness.

3.4.11. Selector Grouping

To apply a style rule to elements in an HTML document of several different types, use selector grouping. Separate with a comma each element type to which the rule is to be applied.

Here's a simple example of this type of selector:

h1, h2, h3 {
  font-family: verdana, arial, sans-serif;
  color: green;
}

The elements in the selector list need not be all of the same type or even of the same level of specificity. For example, the following style rule is perfectly legal. It applies a specific style to level 2 headings (h2) and to paragraphs whose class is defined as special:

h2, p.special {
  font-size: 22px;
}

You may include a space between the comma-separated items or not.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.216.174