Skip to content Skip to sidebar Skip to footer

Css Optimization: Element Id Vs. Class

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 IDs the

Solution 1:

  • 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.

Solution 2:

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.

Post a Comment for "Css Optimization: Element Id Vs. Class"