CSS Best Practices
As stylesheets grow, organisation matters as much as individual property knowledge — consistent naming, sensible file structure, and avoiding overly specific selectors keep CSS maintainable.
A Simple Naming Convention (BEM)
BEM (Block, Element, Modifier) is a popular naming convention that keeps class names predictable and avoids specificity conflicts, since almost everything is styled with a single class selector.
.card { } /* Block */
.card__title { } /* Element — a part of the block */
.card__title--large { } /* Modifier — a variation */
Keeping Selectors Flat
Deeply nested selectors are fragile — they break easily when HTML structure changes and carry unnecessarily high specificity. Favour flat, class-based selectors that describe a component directly.
Common Mistakes
- Writing deeply nested selectors like
.page .content .card .header h3instead of a single flat class. - Mixing multiple naming conventions inconsistently across the same project.
- Duplicating the same values (colours, spacing) throughout a stylesheet instead of using CSS custom properties.
- Leaving unused, dead CSS rules in a growing stylesheet, making it harder to know what's actually safe to remove.
Professional Tip
Pick one naming convention (BEM or otherwise) at the start of a project and apply it consistently, even for small components. The upfront discipline pays off enormously once a stylesheet grows past a few hundred lines.
Your Turn
Refactor a component you've styled earlier in this course (like a card or button) using BEM naming, replacing nested selectors with flat, descriptive class names.
Mini Quiz
In BEM naming, what does the double underscore (__) typically separate?
__ connects a block to an element within it (e.g. card__title), while -- is reserved for modifiers (e.g. card__title--large).