Why CSS architecture matters
In CSS all rules live in one shared space: any selector can affect any element on the page. On a small site this is convenient. In a project with dozens of pages and several developers, the same freedom turns into chaos. CSS architecture is a set of agreements on how to name classes and organize styles so the code stays predictable.
Small and large projects
A one-page landing is easy to keep in your head as a whole. An online store is not: it has hundreds of components, different people write the styles, and the code lives for years. Every new rule can accidentally break something that already works, and checking every page by hand is impossible. That is why large projects write rules not "however it turns out", but by a shared system.
Specificity wars
When a rule does not apply, the easiest thing is to make the selector stronger. Then someone overrides it with an even stronger one — and so on in a circle:
<style>
.sidebar .menu a { color: steelblue; }
.menu-link-red { color: crimson; }
</style>
<nav class="sidebar">
<ul class="menu">
<li><a href="#" class="menu-link-red">This link should be red</a></li>
</ul>
</nav>The link is blue: a selector of two classes and a tag is stronger than a single class. To fix it you would need an even longer selector or !important — this is what a specificity war is.
Name conflicts
Two developers independently came up with a .title class — one for a card, the other for a modal window. The styles get mixed:
<style>
.title { font-size: 22px; color: rebeccapurple; }
/* ...2000 lines later, in another file... */
.title { text-transform: uppercase; }
</style>
<h3 class="title">Card heading</h3>The card heading suddenly became uppercase, although the second rule was written for a completely different component.
Dead CSS
Dead CSS means rules that no longer match anything: the component was removed, but its styles stayed. They are hard to find: the .title class could be used anywhere, so deleting it is scary. As a result stylesheets only grow, even though half of the code has long been unneeded.
What a methodology is
A methodology is a set of rules: how to name classes, which selectors are allowed, how to split styles into files. The best known one is BEM, and most of this chapter is about it. Then we will compare it with OOCSS, SMACSS, ITCSS, utility-first CSS and CSS modules. Cascade layers (@layer) from the previous chapter work well together with any of them.
| Problem | How a methodology helps |
|---|---|
| Specificity wars | all selectors are a single class, of equal strength |
| Name conflicts | the class name includes the component name |
| Dead CSS | a component's styles live next to it and are deleted with it |
Common mistake
Treating cascade problems with !important. It wins today, but tomorrow someone will need to override it — and will have to write a second, stronger !important. If a rule does not apply, look for the cause in the selectors instead of raising their strength.