HTML and CSS Reference
In-Depth Information
Furthermore, say there is a second rule that uses a custom CSS selector called a class with the name
.alert :
.alert { color: purple; }
How do you think the browser is supposed to render the following tag?
<h1 class=”alert”>Attention site visitors!</h1>
In this situation, the CSS principle of specificity comes into play.
The specificity Principle
A class selector is regarded as being more specific than that of a tag selector, so, in this example, the
text would be purple. The hierarchy of selectors from least to most specific looks like this:
Inline styles
I want to take a look at an example to demonstrate how specificity works. Say that you have a page
like this:
<div id=”content”>
<h1 class=”mainTopic”>When in Doubt, Be Specific!</h1>
Furthermore, assume you declared a CSS rule that made all h1 tags green, like this:
h1 { color: green; }
Now, if the client decides he or she wants h1 tags to be green in general, but those that are within a
mainTopic class to be red, you could keep your original CSS rule and write another, like this:
.mainTopic h1 { color:red; }
Because this CSS rule has a higher specificity, the heading in this section would be red. If, for what-
ever reason, the client decides that this one particular heading has to be purple, you could inject an
inline style into the HTML source code:
<h1 class=”mainTopic” style=”color:purple;”>When in Doubt, Be Specific!</h1>
As noted previously, inline styles are generally frowned upon by web designers because they are
difficult to quickly modify. Specificity is a fundamental principle to keep in mind when you're
debugging your CSS styles.
Search WWH ::

Custom Search