CSS ยท Chapter 44 of 44

CSS Best Practices

Writing maintainable CSS means using meaningful class names, avoiding overly specific or deeply nested selectors, organizing styles logically, and leveraging variables for consistency.

Following a naming convention like BEM, keeping specificity low, and avoiding !important where possible all lead to CSS that's easier to scale and debug.

Syntax
/* .block__element--modifier { } */

Naming and organization

Use clear, descriptive class names (like BEM's block__element--modifier pattern) and group related rules together, ideally split across logical files or sections.

Specificity and maintainability

Avoid deeply nested selectors and !important, which make overriding styles later difficult. Prefer classes over IDs for styling, and use CSS variables for shared values like colors and spacing.

Example 1 (css)
.card { }
.card__title { }
.card--featured { }
Output
Clear, predictable class names describing structure and variation

This BEM-style naming makes relationships between elements and modifiers explicit and easy to maintain.

Key points

  • Use meaningful, consistent class naming conventions like BEM.
  • Prefer classes over IDs for reusable styling.
  • Keep specificity low and avoid !important when possible.
  • Use CSS variables to centralize colors, spacing, and fonts.
๐Ÿ’ก Note: Consistent CSS habits make large codebases far easier to maintain and scale over time.

๐Ÿ“ Quick Quiz

1. What naming convention uses block__element--modifier?

2. Why avoid !important where possible?

3. What helps centralize colors and spacing values across a project?