Quick Tip: Understanding CSS Specificity
videos

Quick Tip: Understanding CSS Specificity

The “C” in CSS stands for cascading. This means that that style rules that show up later in the stylesheet will override rules which appear earlier. But this isn’t always the case. There’s something else you have to take into consideration, as well: specificity. In this quick tip, I’ll show you how to do just that.


Specificity Rules

CSS Specificity is basically this: the more specific your selector is, the more precedence it will have. To figure out which selectors are worth more, use this system:

  • Give each HTML element selector 1 point. Example: p
  • Give each class selector 10 points. Example: .column
  • Give each id selector 100 point. Example: #wrap
  • Add up the points for each piece of the selector to get the full value of the selector.

For Example

#test { background: red; } /* specificity : 100 */

.item p { background: green; } /* specificity : 10 + 1 = 11 */

p { background: orange; } /* specificity : 1  */

body #wrap p { background: yellow; } /* specificity : 1 + 100 + 1 = 102 */

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.ifadey.com Fawad Hassan

    Very nice quick tip.
    For those who want to go in depth, check this out:

    http://www.smashingmagazine.com/2010/04/07/css-specificity-and-inheritance/

    :)

  • http://conecode.com Chris

    You mean there’s math involved?

    Thanks for the formula.

  • http://www.daniel-petrie.com Daniel Petrie

    Hmm, never thought of it as a point system before. Interesting way to look at it and figuring out precedence.

  • http://www.purplecoffee.co.uk Gareth Evans

    Nice to know. Would’ve been good to mention the !important tag also, would fit in nicely here.

    • w1sh

      For those of you who don’t know what the !important tag is, you can basically put !important after any style property to over-ride specificity.

      It’s generally used as a way of testing whether or not something is a specificity problem and shouldn’t be used in your final site.

      Get bored: http://www.w3.org/TR/CSS2/cascade.html#important-rules

      Here’s an example:
      body #wrapper { background: red; } /* 1 + 100 */
      #wrapper { background: orange; } /* 100 */

      “Derp! Why isn’t #wrapper inheriting orange?! Is it covered by a div or is it a clearfix problem? Wtf?! …… I know! I’ll test it’s speciftyiciitt6yi with !important!”

      #wrapper { background: orange !important; } /* 100 + INFINITY!!!! */

      “Eureka! It works! So now I need to give that element a higher specifityiadtitittitityyycc than ‘body #wrapper’ and it should work.”

      body #wrapper { background: red; } /* 1 + 100 */
      #wrapper .work-you-friggin-bg { background: orange; } /* 100 + 10 */

      • dru

        Hilarious! Thanks w1sh.

  • http://www.dawn-designs.fr p0ulpe

    Nice video !

  • http://twitter.com/mikeyisfresh Mike

    very nice tutorial!
    you just saved me 1000 headaches!

  • http://kemitchell.com K

    You might mention that there is another way of affecting how precedence is determined: !important rules.

    This is actually mentioned in the section before “Calculating a selector’s specificity” in the spec:

    http://www.w3.org/TR/CSS2/cascade.html#important-rules

  • http://www.dawn-designs.fr p0ulpe

    But I have a question.

    Are the numbers (1 for tags, 10 for “class” and 100 for “id”) you put are chosen at random or are they the real numbers ?

    because if we put 11 tag names one after the others, the selector is powerful than a class ?

    sorry for my english.

  • http://www.nickbrowndesign.com Nick Brown

    Great article. I see a lot of people struggle with this.

    One of the things I changed after I learned this is laying out my CSS files according to weight/precedence.

    So basic element styles are at the top, classes below them, and ID’s below them. If laid out like this, the styles that appear later in the stylesheet will almost always be the ones that override.

  • Umar Mirza

    Great article, one of my favourite quick tips.

  • mookyong

    that’s create aritcle.
    thank you.

  • http://tegarmaji.com Tegar

    where the 1, 10, and 100 points system come from?

  • jmarreros

    Thanks, I didn’t know that

  • http://xpressabhi.com abhishek

    I am still confused. Does it really work, i mean it will not override the “C” rules which appear earlier.

  • leo rapirap

    Additional tips to remember CSS Specificity

    Every
    Coder
    Is
    Insane

    Where:
    E – Element = 1
    C – Class = 10
    I – ID = 100
    I – Inline = 1000

    • Richard Cochrane

      Yes, I was also thinking of inline CSS.

      I know that good practice dictates that you shouldn’t really use it aside from quick tests, but a lot of jQuery plugins add inline CSS so I’ve had a few headaches in modifying a plugin to override it’s CSS changes since nothing in your CSS files is going to take precedence (e.g. jCarouselLite – great plugin, just got annoying inline CSS that you can’t override).

    • http://www.khwebdesign.net Kent

      Every Coder Is Insane – I’ll be able to remember that!

  • http://www.pinoyscreencast.com techie.biox

    wow! this is a great! tutorial ..it really helps but is there any other points system on the other tags? are all the other tags are 1 points coz they are a html tags.

  • Sosby

    guessing the idea for this tutorial came from here -> http://www.smashingmagazine.com/2010/04/07/css-specificity-and-inheritance/

  • Amit

    Hey Andrew,

    Could you do a short tip on handling overflows and block contexts so that floats are contained in a cross browser compatible manner? Also, the clearfix method has recently been disqualified. Can you show how to contain floats without clearfix?

    • http://www.kieru.com Rob

      Easiest way I’ve found to handling floated elements in the most cross-browser compatible manner is simply to add ‘display: inline’ to the element. That solves almost all of IEs old buggy floating margin errors. As for containing floats well – you could have your floated elements within a DIV tag with an ‘overflow: hidden’ attribute which would contain them – or you know you could just use clearfix whether it is disqualified or not.

      Who disqualified it anyway?

    • http://andrewburgess.ca Andrew Burgess
      Author

      You might also want to check out Jeffrey Way’s article on this topic a while back:

      http://net.tutsplus.com/tutorials/html-css-techniques/css-fudamentals-containing-children/

  • Kabita

    good one

  • Mohamed Zahran

    Thanks Andrew, that’s really helped me to understand the differences between ID and Class with css and how does it work ;).

  • Gee

    Really useful tip, thank you

  • http://www.xcellence-it.com/ Xcellence IT

    Great CSS tips. Thanks for sharing this….

  • Peter

    It might have been worth pointing out that the points assigned are arbitrary. For example, a selector containing 11 tag names will not be preferred over a single .classname selector. Also, inline styles (as not-recommended as they are) will win over any stylesheet.

    • Cristina Sturm

      !important overrides inline styles. :o

    • http://www.robnixondesigns.com Rob

      To clarify Peter’s point, the points system for specificity is a bit of an abstraction from what’s really going on. One might be tempted to think that a rather unlikely statement such as:

      #header div.nav ul li ul li ul li ul li ul li p {…..}

      would be worth 122 points, but it’s really worth 1-1-12 points. It is not a decimal base system, it’s effectively an infinite base system as there is no carry over from one placeholder to another.

  • http://www.ravi.uxdsign.com Ravikumar V.

    can you make this post in text as we are not permitted to view videos in our offcie ??

  • http://www.jaytillery.com Jay

    Really simple and meaningful screencast. I think the point system works like a charm and will clear up any issues with beginner css developers in the future.

  • http://www.idesignb.com Bryan

    This was very interesting. I never thought of using specificity like this.
    Seems very simple and Andrew explained it very clear

  • Renowned Media

    Here is some further reading on the topic (Don’t let the article name fool you, it contains some of the more advanced stuff as well).

    http://www.renownedmedia.com/blog/introduction-to-css/

  • wayno

    Wow, this is my epiphany of the day. Many thanks.

  • http://www.chrisleah.co.uk Chris

    Great tut, thanks. Oh and from this are you basically saying be MORE specific on items that are not used over and over? Etc..?

  • http://www.russelluresti.com RussellUresti

    The Specificity article seems to get repeated a few times, which is good, because not a lot of people have seen it or understand it. However, ever since Andy Clarke got this slightly wrong on his article Specificity Wars (http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html), the misleading information there has been in circulation, most recently appearing here and in the Smashing Magazine article referenced earlier by Sosby.

    I hope people who read this article also read comments, because I’m going to try to make this a little more accurate.

    To paraphrase Eric Meyer:

    Basically, your CSS specificity numbers are misleading. A selector with 13 element selectors will always have lower specificity than one with a class and an element. The way you have them, they’d be written with specificity values of 13 and 11, but they’re really (0,0,13) and (0,1,1).

    This is because the CSS1 and CSS2 specifications represented the numbers that way and then made an offhand comment about the numbers being in an infinite-base counting system. CSS2.1 adopts the comma separation to reduce confusion– I think I had something to do with that, actually. See the latter half of Link Specificity for an early example of this notation.

    Oh, and don’t forget that the universal selector (the “*”) has a specificity of 0,0,0. Because, you know– universe, stars, space. Yeah.

    So it’s not quite as easy as a 10 point system, because 13 elements do not override a class, 13 classes do not override an id, and 13 id’s do not override inline styles.

  • James

    I wouldnt recommend using a point system.

    for example:

    body .class WILL override element .class because body is deeper in to the DOM structure.

    just remember:

    element
    path to element
    class
    path to class
    id
    path to id
    inline
    !important
    path to !important

  • http://www.rhysthomas.co.uk Rhys

    Very Nice! Will have to make some notes….

  • Dru

    Did I hear an “Aboot” in there?!? Glad to hear our (US) neighbors to the north are turning out lovely informative tuts! Cheers!

  • Jota Carlos

    Great tip. I’m having some troubles like this. But now I dont.

  • http://codendesign.blogspot.com nXqd

    This is really a good video :) .

  • Nuruzzaman Sheikh

    @Andrew
    very good math. fantastic

    @leo rapirap
    Very useful trick

  • http://whatiscss.michaelfokken.com/ Michael Fokken

    I’ve been learning CSS online, so I never took any classes. That may be a good thing, that may be a bad thing. But thank you for explaining this. That may explain why I couldn’t get a certain div or element to be formatted the way I wanted it. I also never knew that the farther down the document of a CSS overides the previous values.

  • http://codepsd.si CodePsd.com

    @w1sh
    I totaly agree. !important should only be used for testing. And should be avoided as much as possible there too. Without firebug or similar tools it’s very hard to detect what’s wrong if you use it.

  • http://webtutorialplus.blogspot.com/ Henry

    Using class especially to unordered list save a lot of styling headaches.
    Great information!!

  • Cleveland

    How is it possible that you work with code every day so that you can teach about it and, however, you are not good enough to record a video with a few typing errors??? How is it possible making always the same mistake when typing the property and then its value?? Learn to type before you try to teach.

  • http://www.testshoot.com/ TestShoot

    how about using >