Specificity
Given that it is possible to use multiple stylesheets in an HTML document it is inevitable that sooner or later the same CSS selector will be inconsistently defined in different stylesheets. In such situations the browser will apply the CSS rule that has the greatest specificity to the context at hand. Specificity is a complex subject and much has been written on it. The example below illustrates some of the subtleties involved
<html>
<head>
<style>
div{color:red}
div{color:blue}
.one{color:black}
.one a{color:fuchsia}
a{color:maroon}
</style>
</head>
<body>
<div>
Some text and an <a href="anchor.html">anchor</a>
</div>
<div class="one">
Some text and an <a href="anchor.html">anchor</a>
</div>
<div class="one" style="color:gray">
Some text and an <a href="anchor.html">anchor</a>
</div>
</body>
</html>
- There are two rules that define the color of text in a div element. In this case the last definition determines the actual color of text in the first div element.
- The color of anchor elements is defined as being maroon and this turns out to be the case with the anchor in the first div.
- The second div contains a
class="one"declaration. Here the text content of the div are shown in black, as indicated by the definition of the style rule one. The contents of the inline anchor are shown in fuchsia since the.one a{color:fuchsia}style rule is deemed to be more specific to that anchor than the nakeda{color:maroon}declaration even though it is defined later. - The third div is nearly identical to the second one but it contains an inline style definition. In this case it is the inline style that is deemed to be most specific and the text contents of the div are rendered gray.
- A subtle point here - on this site we use an SSI include to import external stylesheets into each page. The SSI directive must be placed after the locally defined styles or else the page rendition goes subtly wrong.