Sometimes we cannot get the effect that we want with CSS due to some cascade and specificity problems. The first and most noticeable problem is that related to inline styles. Inline styles are those attached to a single HTML element through the style
attribute. According to CSS specifications, these styles take precedence over other styles. For example, if you have the following markup:
<p style="color: red;">Test</p>
with this CSS rule:
p { color: blue; }
The text of the paragraph is still red because of the higher specificity of inline styles. If you want to override them, you have to use the !important
statement, like so:
p { color: blue !important; }
You can use this statement in many cases, but not in all. Suppose that your template contains the following rule:
#wrapper .post { font-size: 1.2em; }
An innocent coder would be tempted to use the !important
statement, as follows:
.post { font-size: 1em !important; }
It doesn't work, because the former rule is still more specific than the latter. Instead, you have to write:
#wrapper .post { font-size: 1em !important; }
Also remember that the source code order is relevant: if two rules have the same specificity, the winner is the rules that comes after in the source. This also applies to the source code position of stylesheets: if all the embedded styles are put within the style
element, make sure that your linked styles (via the link
element) come after this element, like so:
<head> <style type="text/css"> ... </style> <link rel="stylesheet" href="http://mywebspace.com/style/blogger.css" type="text/css" media="screen" /> </head>
By doing so, your styles can actually override the others in case of rules with the same specificity.
I don't think that when using:
#wrapper .post { font-size: 1.2em; }
.post { font-size: 1em !important; }
the former rule still "wins". According to the spec (6.4.1), the specificity of the selector has less precedence than the sorting by importance and origin. A test case http://brunildo.org/test/test/important.html seems to confirm that all browsers agree here.