How Style Sheets Work

The key to working with style sheets is understanding how to define rules and then attach those rules to one or more HTML documents.

Rule Syntax

Style sheets consist of one or more rules for describing how a page element should be displayed. The following sample contains two rules. The first makes all the H1s in a document red; the second specifies that paragraphs should be set in 12 pixel high Verdana or some sans-serif font:

H1 {color: red}
P {font-size: 12px;
   font-family: Verdana, sans-serif;
   }

Figure 17-1 shows the components of a style sheet rule.

Parts of a style sheet rule

Figure 17-1. Parts of a style sheet rule

The two main sections are the selector (which identifies the element to be affected) and the declaration (the style or display instructions to be applied to that element). In the sample code above, H1 and P are the selectors. The different types of selectors that may be used are discussed in Section 17.3 of this chapter.

The declaration, enclosed in curly brackets, is made up of a property and its value . Properties are separated from their values by the colon (:) character followed by a space. A property is a stylistic parameter that can be defined, such as color, font-family, or line-height.

A declaration may contain several property/value pairs. Multiple properties must be separated by semicolons (;). Technically, the last property in a string does not require ...

Get Web Design in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.