21

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.

3
  • You mean the actual rendering of the element or querying for the element in the DOM? Commented Jun 24, 2015 at 12:44
  • I did use the word rendering in the question, but I guess I'm really thinking about querying the DOM in order to render. Commented Jun 24, 2015 at 16:02
  • 1
    I know you are asking about rendering speed. That said there are other considerations. Keep in mind, of course, there are semantic reasons to use ID instead of class. I'm not sure that matters for screen readers and accessibility. Of course if using JavaScript to query page, IDs will be faster, but on most pages of reasonable size it's probably negligible. I increasingly see over-use of classes in markup/CSS, and I'm not sure why, when in cases where there is a unique element an ID will do. Commented Mar 15, 2023 at 13:33

1 Answer 1

28

https://web.archive.org/web/20190901050026/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: https://web.archive.org/web/20190901050026/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

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.