Class Selectors: Pinpoint Control

When you don't want every instance of a paragraph or heading tag to get the same styling, CSS lets you create a class selector with a name of your choosing, and then selectively apply it to certain bits of HTML on your page. For example, you can create a class style named .copyright and then apply it only to a paragraph containing copyright information, without affecting any other paragraphs.

Class selectors also let you pinpoint an exact element on a page, regardless of its tag. Say you want to format a word or two inside of a paragraph, for example. In this case, you don't want the entire <p> tag affected, just a single phrase inside it, so you can use a class selector to indicate just those words. You can even use a class selector to apply the same formatting to multiple elements that have different HTML tags. For example, you can give one paragraph and one second-level heading the same styling—perhaps a color and a font that you've selected to highlight special information, as shown in Figure 3-3. Unlike tag selectors which limit you to the existing HTML tags on the page, you can create as many class selectors as you like and put them anywhere you want.

Note

When you want to apply a class selector to just a few words contained inside another tag (like the middle paragraph in Figure 3-3), you need a little help from the <span> tag (Section 1.2.2). See the box in Section 3.1 for more detail.

You've probably noticed the period that starts every ...

Get CSS: The Missing Manual 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.