In Short, Specificity
From CSS Specificity: Things You Should Know:
- Specificity determines, which CSS rule is applied by the browsers.
- Specificity is usually the reason why your CSS-rules don't apply to some elements, although you think they should.
- Every selector has its place in the specificity hierarchy.
- If two selectors apply to the same element, the one with higher specificity wins.
- There are four distinct categories which define the specificity level of a given selector: inline styles, IDs, classes+attributes and elements.
- You can understand specificity if you love Star Wars: CSS Specificity Wars.
- You can understand specificity if you love poker: CSS Specificity for Poker Players.
- When selectors have an equal specificity value, the latest rule is the one that counts.
- When selectors have an unequal specificity value, the more specific rule is the one that counts.
- Rules with more specific selectors have a greater specificity.
- The last rule defined overrides any previous, conflicting rules.
- The embedded style sheet has a greater specificity than other rules.
- ID selectors have a higher specificity than attribute selectors.
- You should always try to use IDs to increase the specificity.
- A class selector beats any number of element selectors.
- The universal selector and inherited selectors have a specificity of 0, 0, 0, 0.
- You can calculate CSS specificity with CSS Specificity Calculator.
For example
If you had a p
with class a
, what would you predict it's color would be based on the following rules:
<!-- language: lang-css -->
p.a { color: red; }
.a { color: blue; }
If you said blue, you'd be wrong!
As Alochi pointed out, if you're looking for more of a Tree View of the styles hit by a particular element, in the Chrome Developer Tools, go to the computed tab and expand the property you're interested in. You'll get a full list of all the other rules that apply to that element with a link to each. From what you know about specificity and cascading, it should be clearer why the "winner" was chosen.