13.3. Understanding Selectors

Selectors are essentially patterns that enable a user agent to identify what elements get what styles. For example, the following style in effect says, "If it is a paragraph tag, give it this style":

p { text-indent: 2em; }

The selector is the first element before the brace, in this case, p (which matches the <p> tag).

This section shows you how to construct selectors of different types to best match styles to your elements within your documents.

13.3.1. Matching Elements by Name

The easiest selector to understand is the plain element selector, as in the following example:

h1 { color: red; }

Using the actual element name (h1) as the selector causes all occurrences of those tags to be formatted with the property/values section of the definition (color: red). You can also specify multiple selectors by listing them all in the selector area, separated by commas. For example, this definition will affect all levels of heading tags in the document:

h1, h2, h3, 4h, h5, h6 { color: red; }

13.3.2. Matching Using the Universal Selector

The universal selector can be used to match any element in the document. The universal selector is an asterisk (*). As an extreme example, you can use the universal selector to match every tag in a document:

* { color: red; }

Every tag will have the color: red property/value applied to it. Of course, you would rarely want a definition to apply to all elements of a document—you can also use the universal selector to match other ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.