A rule, or rule set, is a statement that tells browsers how to render particular elements on an HTML page. A rule set consists of a selector followed by a declaration block. Inside the declaration block, there can be one or more declarations. Each declaration contains a property and a value as shown in Figure 2.1. Figure 2.1. Diagram of rule set structure.
The first step in creating a rule set is to decide on a selector. The selector "selects" the elements on an HTML page that are affected by the rule set. The selector consists of everything up to (but not including) the first left curly bracket. The selectors used in this lesson are shown in Listing 2.2. Selectors are discussed in more detail in Lesson 3, "Selectors in Action." Listing 2.2. CSS Code Showing Selectorsh1 h2 p Next, the declaration block must be created. A declaration block is a container that consists of everything between (and including) the curly brackets. The declaration blocks used in this lesson are highlighted in Listing 2.3. Listing 2.3. CSS Code Showing Declaration Blocksh1 {...} h2 {...} p {...} Inside the declaration block, there are one or more declarations. Declarations tell a browser how to draw any element on a page that is selected. A declaration consists of a property and one or more values, separated by a colon. The end of each declaration is indicated with a semicolon. The declarations used in this lesson are highlighted in Listing 2.4. Listing 2.4. CSS Code Showing Declarationsh1 { text-align: center; } h2 { font-style: italic; } p { color: maroon; }
Listing 2.5. CSS Code Showing Single-Line Rule Seth2 { font-style: italic; text-align: center; color: navy; } Listing 2.6. CSS Code Showing Multiple-Line Rule Seth2 { font-style: italic; text-align: center; color: navy; } The property is an aspect of the element that you are choosing to style. There can be only one property within each declaration unless a shorthand property is used (see "Using Shorthand Properties," later in this lesson). The properties used in this lesson are highlighted in bold in Listing 2.7. Listing 2.7. CSS Code Showing Propertiesh1 { text-align: center; } h2 { font-style: italic; } p { color: maroon; } h1 { text-align: center; } h2 { font-style: italic; } p { color: maroon; } The value is the exact style you want to set for the property. Values can include length, percentage, color, url, keyword, and shape. The values used in this lesson are highlighted (in bold) in Listing 2.8. Listing 2.8. CSS Code Showing Valuesh1 { text-align: center; } h2 { font-style: italic; } p { color: maroon; } The first rule set will target the <h1> element and align it in the center of the browser window. The second rule set will target the <h2> element and render it in italics. The third selector will target the <p> element and color all the text inside the element maroon. The results of this styling applied to the HTML code in Listing 2.1 are shown in Figure 2.2. Figure 2.2. Screenshot of styled elements.
|