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.
ID's used correctly are faster, but with such a minimal difference vs classes - it's not worth any consideration.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With