processing speed difference between CSS class and id

前端 未结 1 1566
北恋
北恋 2021-02-08 07:10

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 ha

1条回答
  •  难免孤独
    2021-02-08 07:49

    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

    0 讨论(0)
提交回复
热议问题