Sub topic 1
Why CSS Gets Hard to Maintain at Scale
Prerequisites
You should know CSS selectors, inheritance, the box model, and the basic cascade. You should also be comfortable reading HTML and linking a stylesheet to a page.
Why CSS Gets Hard to Maintain at Scale
CSS is global by default. A selector written for one page can affect another page when both use the same class name. As a codebase grows, styles accumulate and their relationships become difficult to see.
Three forces cause most problems:
- Scope: rules can affect more elements than intended.
- Specificity: more specific selectors override simpler selectors.
- Source order: when specificity is equal, the later rule wins.
A small change can therefore fix one component while breaking another. Developers may add longer selectors or !important, which makes future changes harder.
Managing the Cascade, Specificity and Source Order
Treat specificity as a limited budget. Prefer one-class selectors and make the intended order explicit.
.card {
padding: 1rem;
border: 1px solid #ddd;
}
.card--featured {
border-color: gold;
}Both selectors have low specificity. If both rules match, source order decides the result. Avoid selectors such as main .dashboard .card h2, because they are difficult to override without writing an even stronger selector.
Naming Things So Styles Stay Predictable
Names should describe a component's role rather than its appearance. A name such as .card remains useful when its color or layout changes. A name such as .blue-box records an implementation detail that may soon become false.
Use a consistent convention for components, states, and inner parts. Predictable names make searching, reviewing, and deleting CSS safer.
Building Components with BEM
BEM is a naming convention:
- A block is an independent component, such as
card. - An element is a part of that block, such as
card__title. - A modifier changes the block or element, such as
card--featured.
<article class="card card--featured">
<h2 class="card__title">Release notes</h2>
<p class="card__body">What changed this week.</p>
</article>BEM does not remove the cascade. It gives selectors a predictable scope and keeps them easy to override.
Exercise
Why is .card--featured preferable to article.dashboard .card.special for a card variation?
Show answer
It has lower, predictable specificity and states the component variation directly, so it is easier to override and reuse.