- If the selectors are the same then the latest one will always take precedence.
- The more specific a selector, the more preference it will be given when it comes to conflicting styles.
- The embedded style sheet has a greater specificity than other rules.
Specificity hierarchy
Every selector has its place in the specificity hierarchy. There are four distinct categories which define the specificity level of a given selector:- Inline styles (Presence of style in document).
An inline style lives within your XHTML document. It is attached directly to the element to be styled. E.g.<h1 style="color: #fff;"> - IDs (# of ID selectors)
ID is an identifier for your page elements, such as#div. - Classes, attributes and pseudo-classes (# of class selectors).
This group includes.classes,[attributes]and pseudo-classes such as:hover,:focusetc. - Elements and pseudo-elements (# of Element (type) selectors).
Including for instance:beforeand:after.
phas a specificity of 1 (1 HTML selector)div phas a specificity of 2 (2 HTML selectors; 1+1).treehas a specificity of 10 (1 class selector)div p.treehas a specificity of 12 (2 HTML selectors and a class selector; 1+1+10)#baobabhas a specificity of 100 (1 id selector)body #content .alternative phas a specificity of 112 (HTML selector, id selector, class selector, HTML selector; 1+100+10+1)
div p.tree (with a specificity of 12) would win out over div p (with a specificity of 2) and body #content .alternative p would win out over all of them, regardless of the order.What is what
p inp { padding: 10px; }
p.section inp.section { padding: 10px; } p#section in#section { padding: 10px; }
(X)HTML: <p id="section">Text</>p span inp span { font-style: italic; }
defines that all span-elements within a p-element should be styled in italics.
p span inp[title] { font-weight: bold; }
matches all p-elements which have a
title attribute.:visited ina:visited {
text-decoration: underline;
}
:first-line or :after inp:first-line {
font-variant: small-caps;
}
a:link:after { content: " (" attr(href) ")"; }
My thanks to
http://htmldog.com/guides/cssadvanced/specificity/
http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
Future reading:
Inheritance
http://www.smashingmagazine.com/2010/04/07/css-specificity-and-inheritance/
