I have this (simplified) markup:
<ul id="topnav">
<li>one</li>
<li>two</li>
<li id="last-nav">last</li>
</ul>
and these CSS rules:
#topnav li {
list-style-type: none;
float: left;
}
#last-nav {
float: right;
}
To my surprise, the second rule is overruled by the first one. If I change the selector to li#last-nav
, it works. Why is that?
(Disclaimer: I only tested this in Firefox)
Inline CSS has a higher priority than embedded and external CSS. So final Order is: Value defined as Important > Inline >id nesting > id > class nesting > class > tag nesting > tag.
CSS Order Matters In CSS, the order in which we specify our rules matters. If a rule from the same style sheet, with the same level of specificity exists, the rule that is declared last in the CSS document will be the one that is applied.
Properties of CSS: Inline CSS has the highest priority, then comes Internal/Embedded followed by External CSS which has the least priority.
Specificity Rules include:CSS style applied by referencing external stylesheet has lowest precedence and is overridden by Internal and inline CSS. Internal CSS is overridden by inline CSS. Inline CSS has highest priority and overrides all other selectors.
The cascade works like this:
Here, #topnav li
has a specificity of 101, and #last-nav
has a specificity of 100, so the first one wins. A selector of li#last-nav
or #topnav #last-nav
would be more specific.
Read up on CSS Specificity:
http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
http://meyerweb.com/eric/css/link-specificity.html
Essentially, the first selector is more specific than the second, so it takes precedence. It's not about top-down order in CSS. Top-down order only applies if both selectors are equally specific.
Selector Rules: Calculating Specificity
Style sheets can also override conflicting style sheets based on their level of specificity, where a more specific style will always win out over a less specific one. It is simply a counting game to calculate the specificity of a selector.
Finally, write the three numbers in exact order with no spaces or commas to obtain a three digit number. (Note, you may need to convert the numbers to a larger base to end up with three digits.) The final list of numbers corresponding to selectors will easily determine specificity with the higher numbers winning out over lower numbers. Following is a list of selectors sorted by specificity:
#id1 {xxx} /* a=1 b=0 c=0 --> specificity = 100 */
UL UL LI.red {xxx} /* a=0 b=1 c=3 --> specificity = 013 */
LI.red {xxx} /* a=0 b=1 c=1 --> specificity = 011 */
LI {xxx} /* a=0 b=0 c=1 --> specificity = 001 */
In your example #topnav li
is 101 and #last-nav
is only 100, so 101 wins.
Cited from http://htmlhelp.com/reference/css/structure.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With