I am aware than ID rules are faster than class rules, which are faster than tag rules, which are faster than universal rules, as noted on MDN. My question pertains to CSS performance with respect to inheritance. For example, which of the following is more efficient?
body {
font-family: Helvetica, Arial, sans-serif;
font-size: 16px;
}
h1 {
font-family: Georgia, serif;
font-size: 36px;
font-weight: 700;
}
or
h1 {
font-family: Georgia, serif;
font-size: 36px;
font-weight: 700;
}
.article-text {
font-family: Helvetica, Arial, sans-serif;
font-size: 16px;
}
While there is only one <body>
tag in the DOM, there could be hundreds of p.article-text
elements. Since there is only one <body>
tag, does that mean that a <body>
style is more efficient, even though I'd be restyling the <h1>
elements? Or is it more efficient to style the .article-text
elements, since doing so would use a more specific selector and I wouldn't need to worry about restyling the <h1>
elements?
Always wondered this. Thoughts?
I think that the MDN article you showed is written in a harmful way, as it proposes to focus on CSS micro-optimizations while almost always page speed can be increased in different ways (eg. Google Page Speed has interesting hints).
I can't remember any situation in my websites where CSS was a bottleneck. You might want to see "Timeline" in Chrome Developer Tools on some pages and notice that the amount of time spent on working with styles is usually insignificant compared to other events.
If I was to give advice, I'd rather go the other way and use CSS preprocessing tools like SASS or LESS to improve maintainability. This might even eventually help to reduce number of rules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With