Published
on
July 23, 2008
| 1,521 views
| 0 followers
members are following updates on this item.
Aside from floating elements, Specificity is one of the mostdifficult concepts of css to understand. If we look at thedefinition of specificity, the following is probably the bestinterpretation related to CSS:
If you have two (or more) conflicting CSS rules that point tothe same element, there are some basic rules that a browser followsto determine which one is most specific and therefore wins out.
Remember these numbers, there will be a quiz later.
Selector | Value |
---|---|
ID | 100 |
Class | 10 |
HTML | 1 |
Note: * value is equal to zero, along with pseudoelements (hover, link, after, etc.)
So let me give you some css rules.
Rule | Value |
---|---|
p { color: yellow; } | 1 |
p{ color: green; } | 1 |
The values of the first and second rules are 1 (html selector),so the way to break the tie is to lose the race, the last rule wins(same selector, latest one takes precedence) . Paragraphs are Green, and such an ugly shade it is.
Now what about this?
Rule | Value |
---|---|
a p { color: yellow; } | 1 |
p{ color: green; } | 1 |
For starters, what were you thinking, you can't do that. An a(anchor) is an inline element and the p (paragraph) is a blockelement. Block-level elements can contain inline elements not theother way around.
The correct rules.
Rule | Value |
---|---|
div p { color: yellow; } | 1 + 1 |
p{ color: green; } | 1 |
The value of the first rule is 1 (html selector) + 1 (htmlselector) for a total of 2 on the specificity scoreboard. Thesecond rule has a value of 1 (html selector) which can only meanretinal burn Yellow.
Forget everything I just said because if your smart about yourcss and don't create some obscene set of css rules that spans shallwe say 38 Pages then specificity won't be an issue.
Just kidding, specificity is something that you generally won'thave to worry about but is nice to know as it can come in handy forthose larger projects.
Page Options