Primary Navigation
Under the Dome
Specificity, Say That Three Times Fast!
Floating elements aside, CSS Specificity is one of the most difficult concepts to grasp in Cascading Style sheets.
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.
Recent Contributors
Recent Posts
- Breadcrumbs, From Fairy Tales To Reality
10 days ago - Blogs ... Forums ... Which will I be using?
13 days ago - Screen Resolution Vs. Website Design
4 weeks ago - Specificity, Say That Three Times Fast!
4 weeks ago
Page Options
Guest