CSS Optimization: Element ID vs. Class

前端 未结 2 1033
我寻月下人不归
我寻月下人不归 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.

    0 讨论(0)
  • 2020-12-09 05:40

    I generally prefer the class method. The reason being that you don't have to write up a new css selector for each new ID'd element in your system.

    Also, I tend to differentiate between "structure" and "style" css. Meaning, that I separate things that deal with size (width / height) and position from css classes that do font-weight, color, etc.

    For non-changing structural framework pieces, I'll use ID's. For parts that may have multiple representations in the HTML, I'll stick with class mechanisms.

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