Controlling the Cascade

As you can see, the more CSS styles you create, the greater the potential for formatting snafus. For example, you may create a class style specifying a particular font and font-size, but when you apply the style to a paragraph, nothing happens! This kind of problem is usually related to the cascade. Even though you may think that directly applying a class to a tag should apply the class's formatting properties, it may not if there's a style with greater specificity.

You have a couple of options for dealing with this kind of problem. First, you can use !important (as described in the box above) to make sure a property always applies. The !important approach is a bit heavy handed, though, since it's hard to predict that you'll never, ever, want to overrule an !important property someday. Read on for two other cascade-tweaking solutions.

Changing the Specificity

The top picture in Figure 5-4 is an example of a specific tag style losing out in the cascade game. Fortunately, most of the time, you can easily change the specificity of one of the conflicting styles and save !important for real emergencies. In Figure 5-4 (top), two styles format the first paragraph. The class style—.intro—isn't as specific as the #sidebar p style, so .intro's properties don't get applied to the paragraph. To increase the specificity of the class, add the ID name to the style: #sidebar .intro.

Selective Overriding

You can also fine-tune your design by selectively overriding styles ...

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.