Skip to main content

Under the Dome

 
Gary Larocque

Specificity, Say That Three Times Fast!

by Gary Larocque - 4 weeks ago

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.

SelectorValue
ID100
Class10
HTML1

Note: * value is equal to zero, along with pseudo elements (hover, link, after, etc.)

So let me give you some css rules.

RuleValue
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?

RuleValue
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.

RuleValue
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.

Recommend this Article

Average: No Rating Available (0 votes)  

Would you like to comment?

Join for a free account, or Sign In if you are already a member.


Viewed 110 times