Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

processing speed difference between CSS class and id

For this question, I'm only comparing a browser's speed in rendering the CSS on 2 elements which are different only in that one has a class and one has an id.

(This has nothing to do with JS identification, anchor use, etc.)

<div class="myclass">classed element</div>
<div id="myid">ided element</div>

Does anyone have numbers on this? I have read that CSS ids are 'faster,' but by how much? I'm going to hazard a guess that it's negligible, but it would be interesting to know.

like image 552
adam rowe Avatar asked Jun 24 '15 12:06

adam rowe


People also ask

Which is faster ID or class in CSS?

ID's used correctly are faster, but with such a minimal difference vs classes - it's not worth any consideration.

Is ID stronger than class CSS?

ID's are more specific than classes and take precedence over them. This is because ID's have to be UNIQUE on every page...so they are by nature very specific. Classes can appear multiple times.

What is the difference in CSS between an ID and a class?

The difference between an ID and a class is that an ID is only used to identify one single element in our HTML. IDs are only used when one element on the page should have a particular style applied to it. However, a class can be used to identify more than one HTML element.

Does ID or class take priority CSS?

Class and ID selector example If more than one rule applies to an element and specifies the same property, then CSS gives priority to the rule that has the more specific selector. An ID selector is more specific than a class selector, which in turn is more specific than a tag selector.


1 Answers

http://oli.jp/2011/ids/

ID's are faster in some cases, but not all

It’s a common belief that ID selectors are the fastest, but this comes with a big caveat: IDs are fastest CSS selector only if they’re the key selector. What’s that? Well, while you probably read selectors from left to right, browsers read them from right to left.

There's also a performance test here for your numbers request: http://oli.jp/2011/ids/#table1

Conclusion

ID's used correctly are faster, but with such a minimal difference vs classes - it's not worth any consideration.

It seems to me that there are no convincing reasons to use IDs in selectors for CSS styling¹, as CSS classes can do everything IDs can. Hopefully you’ll agree there are some good reasons not to. Think about it the next time you start a personal project or redesign your own site, and try adding a class (or ARIA landmark roles) for styling instead. Save IDs for fragment identifiers or JavaScript hooks

like image 172
Novocaine Avatar answered Sep 20 '22 14:09

Novocaine