CSS Best Practices slideshow:
This note is meant as a guide for writing clean CSS, as well as refactoring bad CSS as you touch code. The problem is that people don't want to touch an old CSS style and break something. So bad styles stick around for a long time. We need to put in the extra effort of getting rid of those bad styles.
Our highest priorities are: + Semantics (readability) + Modularity (reusability, flexibility) + Efficiency (performance) - Keep performance in mind, but don't worry too much about it. The main advantage of using performant selectors is that it increases readability and modularity. For example,
.container *is terrible not just because of performance, but also because it hurts flexibility and requires future styles to use hacky overrides. - Steve Souders examined the performance impact of CSS selectors and determined that the delta between the best case and the worst case was 50ms. In other words, consider selector performance but don’t waste too much time on it. + http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/ - Nicole Sullivan's comment on the above article: "Micro-optimization of selectors is going a bit off track in a performance analysis of CSS. The focus should be on scalable CSS. There are two ways to measure 0(n) in CSS. What happens as you add more pages and modules to the site? Then you measure both file size, and HTTP requests. The way you write selectors has a huge impact on both of these that is much more significant than the time it takes the browser to process a reasonable number of selectors (even deeply nested)."
.loading. This is more reusable, less ambiguous, and easier to find in searches.
.menu.wide. This is easier to reuse and find in searches as well, and harder to create hacky combinations and overrides.
!important. People add it to override styles that are too specific. The correct solution is to avoid too many levels of nesting in the first place, so you never have to use
!important. If you see too much nesting, this is a good place to refactor. If you have to use it, document your use of
button strong span .calloutis like an inheritance tree that's too deep.
button .callout-- this way you can move
.calloutaround more easily in the future and it's not tightly coupled with the DOM tree.
.alert-error,instead of, e.g.
div ul li, any time it draws an
li, it checks if it's in a
ul, then it checks if the
ulis in a
.followers span. They are neither performant, nor flexible for future scenarios where you might not want all spans to have this style. Use classnames instead. This also makes it more semantic and readable.
Below is the order of efficiency for selectors. Id's are the most efficient and pseudo classes and pseudo elements are the least efficient.
Even though id's are more efficient than classes, the difference is extremely small, so opt for classes when you can. Id's have to be unique, while classes are more flexible and reusable.