I\'m trying to learn to write more efficient CSS, particularly as I\'m working with a fairly complex site that needs to render fast.
I\'m used to having a lot of thi
The best trade-off, I think, is using the child combinator >
for elements that are repeated many times and using classes when things start to become too nested.
Bending the Rules of BEM
The above article strikes the perfect balance, I think, considering our options.
Using SCSS, which ought to be obligatory nowadays, my navigation menus usually look like this (which is definitely the most I will ever nest stuff):
.header__nav {
> ul {
> li {
> a {}
}
}
}
You have to weigh it up. Adding a class to every anchor is ridiculous, the extra bloat in the HTML would massively offset the rendering time saved (which would be 1/10,000th of a bee's leg). Not to mention how hard your code would be to maintain.
You just need to stop using unnecessarily expensive selectors, for example
.spotlight ul li a
Can be written as
.spotlight a
If you keep on specifying a single class on the same elements in your HTML (like your second example), you'd probably be better off using a tag selector instead.
You also have to weigh up your time vs the browsers time. How much is it going to cost in your time to save a few nanoseconds on each page load? In all honestly, it's not really worth it.
Also, making your CSS structure match your HTML structure negates the point of CSS - if the HTML changes, you need to change your CSS. So you always want your selectors to be as unspecific as possible.
But there is no right or wrong answer here.