CHAPTER 1 Modern CSS Architecture and Front-End Development
Robustness
If you have long selectors with tons of stuff going on in them then it only
stands to reason that there is, statistically, a higher chance of something
going wrong. Let’s look at an example:
section.content p:first-child {
font-size: 1.333em;
}
Here we have four smaller selectors in one compound selector. That
means there are potentially four places for this code to break. If we change
the section to an article, the selector will break. If we change the class
of .content to .page, the selector will break. If we introduce an element
before that paragraph, the selector will break. Basically, there is a lot to go
wrong because of the size of — and number of parts in — this selector.
A far more robust replacement would be to simply use:
.intro {
font-size: 1.333em;
}
Nothing can go wrong here. The only way we can prevent this selector
from working is to remove it entirely from our markup, and if we do that
then we intend to break it. Keeping selectors shorter keeps them far more
robust, purely by lowering the statistical chance that they can break.
Decrease Specificity
As I mentioned before, specificity is an absolute nightmare. Specificity
is what causes CSS to spiral out of control. Specificity is why we have
!important. Thankfully, by keeping selectors short, you inherently keep
your specificity low. This is a good place to be!
As well as avoiding IDs, we need to avoid adding anything unnecessary
to our selectors. Anything that can be removed from a selector should be.