processing speed difference between CSS class and

2020-06-10 15:32发布

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.

1条回答
我想做一个坏孩纸
2楼-- · 2020-06-10 16:14

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

查看更多
登录 后发表回答