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:
Thanks for your time!
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.