CSS Priority: The Difference Between a.my-class and .my-class

Do You Know What’s an Inefficient CSS Selector?

Perhaps! I was curious how can inefficient selectors impact a page performance. To begin with this topic let me say that inefficient selector is referred usually as nested selector:

div span div {
    border:1px solid red;
}

as you can see here there are three nested tags I use to reference the innermost div. If you’re wondering how you’d know about inefficient selectors – well there is a plugin for the Firebug written by a Google team called Page Speed explaining which of your selectors are inefficient. See the image below.

CSS Page Speed Inefficient Selectors

In the demo page you can find what I was trying to achieve and you can play around with that code to measure by yourself the performance of the different selectors.

So who’s faster? Nested, IDs or Classes?

Actually its pretty though to say. Yet another surprise for me was to notice that the notation:

div.my-class {}

was a bit slower than the marked as “inefficient” by Page Speed:

div span div {}

Another good thing to mention is that there is a difference between div.my-class and .my-class

Question’s answer …

In fact div.my-class is always with a higher priority than .my-class even if you’ve the following code:

div.my-class {
    border:1px solid red;
}
 
.my-class {
    border:1px solid blue;
}
 
div span div {
    border:1px solid black;
}

And the computed style for Firefox was …

CSS Selector Performance Computed Style

where “div span div” chain matches the same elements as the previous selectors, as you can see:

CSS Selector DOM View

so even that div.my-class will be the most important and finally the element will get its red border! It does not depend only on where you put the CSS rules, but also on how they are defined.

3 thoughts on “CSS Priority: The Difference Between a.my-class and .my-class

  1. Hi Stoimen,

    nice post again, thanks. But there’s a problem – I ran out the code you posted and my browser was totally down? I couldn’t get any results?!

    Do you know what may be the problem?

Leave a Reply

Your email address will not be published. Required fields are marked *