Question

What's better for general CSS usage? I'm showing a specific example, but the question is more geared towards general application of this in any situation.

table.class tbody tr td.class2 {
    stuff;
}

OR

td.class2 {
    same stuff;
}

(If the only td.class2's always have the parents: table.class tbody tr.)

I assume the second one is faster, unless maybe in some extreme situation where there are a lot of tables with wild rules, dependencies and similar. The first one is more specific, so it makes things more clear, but I assume when there are a lot of those it can be hard to keep track of it.


Which one is better when writing CSS? I assume it depends on the context:

  1. As a generally good policy.
  2. Web page that doesn't have an overwhelming amount of visitors and content.
  3. Web page that doesn't have an overwhelming amount of visitors, but does have a fairly high amount of tables and content.
  4. Web page that does have an overwhelming amount of visitors, but doesn't have a fairly high amount of tables and content.
  5. Web page that does have an overwhelming amount of visitors and content.

Thanks for your time!

Was it helpful?

Solution

Optimize browser rendering on Google Developers has a good article covering this. One key point highlighted twice in that pos that you should always remember is:

The engine evaluates each rule from right to left, starting from the rightmost selector (called the "key") and moving through each selector until it finds a match or discards the rule.

and

According to this system, the fewer rules the engine has to evaluate the better.

Writing Efficient CSS on the Mozilla Developer Network also covers this topic.

So the second one is more efficient in all of your 5 cases since the browser will be doing less work regardless of the amount of content.

In general, I see "optimised CSS" as reduction of the chain depth of CSS selectors to minimize the dependency on the HTML structure. This principle and more is covered in the excellent Scalable and Modular Architecture for CSS (SMACSS), which is essentially a style guide for CSS and not a framework or anything like that. In particular I would take a look at the Selector Performance and Depth of Applicability sections.

OTHER TIPS

Well as a good first bet you would want the smallest file size possible. By that I mean, You would ideally want a structure that fits your needs, ala makes your website have the correct look, and is the smallest possible size.

the first method you mentioned is good when you have multiple class2 elements in different parent structures which require a different layout. That being said the second method is sufficient if all class2 elements reside in the same parent structure and general layout, and would reduce overall size and increase speed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top