CSS Optimization: Element ID vs. Class

前端 未结 2 1032
我寻月下人不归
我寻月下人不归 2020-12-09 04:39

With MVC and jQuery I am making significantly more use of CSS. A question that came to mind is what is the best approach for using Element IDs vs. Classes. If I use Element

2条回答
  •  庸人自扰
    2020-12-09 05:40

    • IDs are the fastest
    • Tag names are next fastest
    • Class names with no tag name are the slowest

    As for which one to use, use whichever is most appropriate. If you have a search box on your page then using an ID for that would be most appropriate because there's only one search box. Table rows on the other hand will probably be identified by class because there is (or can be) more than one.

    Try not to use selectors (in CSS or jQuery) like ".class". You're forcing jQuery or the browser to basically traverse the entire document tree. Most of the time the class will only apply to one kind of tag so specify that (eg "div.class"). That alone can make a huge performance difference (particularly on jQuery with a large document).

    The length of the selector should not be a consideration. Performance, readability and maintainability should be.

提交回复
热议问题