Primary Navigation
CSS - Specificity
Aside from floating elements, Specificity is one of the most difficult concepts of css to understand. If we look at the definition of specificity, the following is probably the best interpretation related to CSS:
- Specificity
- a type of weighting that has a bearing on how your cascading style sheet (CSS) rules are displayed.
The Important Stuff
If you have two (or more) conflicting CSS rules that point to the same element, there are some basic rules that a browser follows to 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 pseudo elements (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 block element. Block-level elements can contain inline elements not the other 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 (html selector) for a total of 2 on the specificity scoreboard. The second rule has a value of 1 (html selector) which can only mean retinal burn Yellow.
Now The Real Important Stuff
Forget everything I just said because if your smart about your css and don't create some obscene set of css rules that spans shall we say 38 Pages then specificity won't be an issue.
Just kidding, specificity is something that you generally won't have to worry about but is nice to know as it can come in handy for those larger projects.
- 148 views
- 2 versions
- 0 comments
- 1 follower
- Post Date:
- December 6, 2011
- Posted By:
- Gary Larocque
- Versions:
- v.2
Page Options
0 Comments
Would you like to comment?
You must be a member. Sign In if you are already a member.