Phase 5Tooling & Production

#18 CSS architecture

BEM, utility-first, CSS Modules

Why CSS architecture matters

As projects grow, unstructured CSS becomes unmaintainable. CSS architecture provides conventions to keep styles organized, predictable, and scalable.

BEM methodology

BEM (Block, Element, Modifier) is a naming convention that makes CSS classes descriptive and structured:

BEM naming
/* Block */
.card { }

/* Element (belongs to block) */
.card__title { }
.card__body { }
.card__image { }

/* Modifier (variant of block/element) */
.card--featured { }
.card__title--large { }

/* HTML */
<div class="card card--featured">
  <img class="card__image" src="..." alt="...">
  <h3 class="card__title card__title--large">Title</h3>
  <p class="card__body">Content</p>
</div>

Utility-first CSS

Utility-first (like Tailwind CSS) uses small, single-purpose classes:

Utility classes
/* Utility classes */
.flex { display: flex; }
.items-center { align-items: center; }
.gap-4 { gap: 16px; }
.p-4 { padding: 16px; }
.rounded-lg { border-radius: 12px; }
.bg-blue { background: #3b82f6; }
.text-white { color: white; }

/* Usage */
<button class="flex items-center gap-4 p-4 rounded-lg bg-blue text-white">
  Click me
</button>

CSS Modules

CSS Modules (React/Next.js)
/* Button.module.css */
.button {
  background: #3b82f6;
  color: white;
  padding: 12px 24px;
}

.primary {
  background: #3b82f6;
}

.secondary {
  background: #6b7280;
}

// Button.tsx
import styles from './Button.module.css'

export function Button({ variant = 'primary' }) {
  return (
    <button className={`${styles.button} ${styles[variant]}`}>
      Click me
    </button>
  )
}

File organization

Recommended structure
styles/
  _variables.scss      # Colors, spacing, fonts
  _mixins.scss         # Reusable mixins
  _reset.scss          # CSS reset / normalize
  _base.scss           # Base element styles
  _typography.scss     # Font styles
  _layout.scss         # Grid, container
  components/
    _button.scss
    _card.scss
    _navbar.scss
  pages/
    _home.scss
    _about.scss
  main.scss            # Entry point, imports all

Your turn

Try the CSS architecture commands below:

terminal — npm
user@stemlegacy:~/my-project$