Css architecture

From FerroxLabs/murage · View interactive version

Css architecture is an AI agent skill from the GitHub repository FerroxLabs/murage. Guides expert-level css architecture implementation: html-css and web-development decision frameworks, production-ready patterns, and concrete templates for css architecture workflows. Use when the user asks about css architecture, css architecture configuration, or html-css best practices for css p

How to use this skill

Skill file

CSS Architecture

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Assess Project Context and Scale

Before recommending any methodology, gather four critical dimensions:

2. Choose an Architecture Methodology

Apply the following decision framework based on context:

Avoid mixing methodologies within a single codebase. A project can layer ITCSS + BEM (common) or Tailwind + CSS Modules for component internals, but should not mix BEM globals with CSS-in-JS component files arbitrarily.

3. Design the Token and Variable System

CSS custom properties are the foundation of any scalable architecture. Structure them in three tiers:

Define Tier 1 and Tier 2 tokens in :root. Define Tier 3 tokens in the component selector scope. This structure enables theming at any level: override :root variables for dark mode, override component variables for variants.

4. Establish the File and Folder Structure

For ITCSS-based projects using Sass/PostCSS, use this canonical folder structure:

styles/
├── settings/
│   ├── _tokens.scss        # Design tokens (colors, spacing, type scale)
│   └── _breakpoints.scss   # Breakpoint values only
├── tools/
│   ├── _mixins.scss        # Reusable mixins
│   └── _functions.scss     # Sass functions (e.g., px-to-rem)
├── generic/
│   ├── _reset.scss         # box-sizing, margin/padding reset
│   └── _normalize.scss     # Browser normalization
├── elements/
│   ├── _typography.scss    # h1–h6, p, a, ul, ol bare styles
│   └── _forms.scss         # input, button, select bare styles
├── objects/
│   ├── _container.scss     # Max-width wrapper
│   ├── _grid.scss          # Layout grid object
│   └── _media.scss         # Media object (image + text pattern)
├── components/
│   ├── _button.scss
│   ├── _card.scss
│   └── _nav.scss
├── utilities/
│   ├── _spacing.scss       # Margin/padding utility classes
│   └── _visibility.scss    # Screen-reader-only, hidden
└── main.scss               # Imports in ITCSS order

For CSS Modules projects, co-locate module files with components:

components/
├── Button/
│   ├── Button.tsx
│   ├── Button.module.css
│   └── Button.test.tsx
├── Card/
│   ├── Card.tsx
│   └── Card.module.css
styles/
├── tokens.css              # :root custom properties (global)
├── reset.css               # Global reset
└── typography.css          # Base type styles

5. Configure Tooling and Linting

CSS architecture enforcement requires tooling. Configure these tools:

6. Implement Specificity Management

Specificity is the most common source of CSS maintenance pain. Apply these rules:

7. Define Naming Conventions and Documentation

Conventions must be written down, not assumed:

8. Establish a Review and Refactoring Process

CSS architecture degrades without active maintenance:


Output Format

When responding to a CSS architecture request, structure the output as follows:

## CSS Architecture Assessment

### Project Profile
- **Team size:** [number]
- **Application type:** [SPA / SSR / static / hybrid]
- **Component framework:** [React / Vue / Svelte / none]
- **Existing CSS approach:** [describe current state]
- **Key constraints:** [browser support, performance budget, team experience]

### Recommended Architecture

| Dimension            | Recommendation         | Rationale                              |
|----------------------|------------------------|----------------------------------------|
| Methodology          | [BEM / ITCSS / Modules | Why this fits the project profile      |
| Token system         | [CSS custom properties | Structure: primitive > semantic > comp |
| Tooling              | [PostCSS / Sass / etc] | Why this tooling fits the stack        |
| Specificity strategy | [@layer / flat BEM]    | How specificity will be managed        |
| File structure       | [ITCSS / co-located]   | How files will be organized            |

### Implementation Plan

#### Phase 1: Foundation (Week 1)
[Concrete steps for establishing tokens, reset, and file structure]

#### Phase 2: Component Migration (Weeks 2–4)
[Strategy for writing or migrating components under the new system]

#### Phase 3: Tooling and Enforcement (Week 2 alongside Phase 2)
[Stylelint config, CI integration, bundle budgets]

### File Structure

[Annotated folder tree for this specific project]

### Token Structure

[CSS custom property declarations for Tier 1, 2, and 3 tokens]

### Stylelint Configuration

[stylelint.config.js with rules specific to the chosen methodology]

### Critical Decisions and Trade-offs

[Numbered list of key choices made and what was rejected and why]

### Maintenance Guidelines

[Rules the team should follow, written as enforced conventions]

Rules

  1. Never mix BEM global selectors with unscoped CSS Modules in the same component. If a component uses a .module.css file, all its styles must live in that file. Placing additional BEM classes for the same component in a global stylesheet creates two sources of truth and guarantees drift.
  1. Never use ID selectors (#id) in stylesheets. IDs have a specificity of (1,0,0), which defeats any flat-specificity strategy. IDs belong in HTML for accessibility (aria targets, fragment links) but never as CSS selectors.
  1. Never hardcode color, spacing, or typography values in component files. Every non-zero value for these properties must reference a CSS custom property or Sass variable. A raw hex code or pixel value in a component file is a design token system violation and creates future inconsistency.
  1. Always define browser support targets before choosing a CSS feature. @layer, container queries, CSS nesting, and :has() have varying support thresholds. Check the project's browser support matrix (usually defined in .browserslistrc) before using any feature. Use postcss-preset-env to polyfill or transpile where support is insufficient.
  1. Never nest selectors more than 2 levels deep in Sass/PostCSS, even when the language allows it. Deep nesting generates high-specificity selectors and makes the generated CSS unreadable. BEM eliminates the need for nesting by encoding hierarchy in class names.
  1. Always configure Stylelint in CI with zero-tolerance for errors. A Stylelint warning that does not block a PR will be ignored. CSS architecture only holds at team scale when violations are caught automatically. Warnings can be used during migration; they must be resolved before they can stay as permanent configuration.
  1. Never use !important in component or object CSS. The only acceptable uses of !important are: in utility classes (where it is the mechanism for override), in accessibility-driven overrides (forced-colors media query), or in third-party override stylesheets that cannot change the third-party source. All three must be documented with a comment explaining why.
  1. Always extract critical CSS for server-rendered or statically generated pages. For any page where Largest Contentful Paint (LCP) is a priority, the CSS required to render above-the-fold content must be inlined in the <head>. Failing to do this forces the browser to block rendering while fetching an external stylesheet.
  1. Never delete a CSS class without searching for its usage across HTML templates, JavaScript, and test files. Tools like grep, ripgrep, or IDE project-wide search must confirm zero references. Automated dead-code detection (PurgeCSS, UnCSS) provides confidence but can miss dynamically constructed class names in JavaScript.
  1. Always write CSS custom property fallback values during migration periods. When replacing a hardcoded value with a token (color: var(--color-action-primary, #3b82f6)), include the fallback during the transition. Remove fallbacks only after confirming the token is defined in all environments (including production builds and Storybook).

Edge Cases

Legacy Codebase with Accumulated Specificity Debt

When a codebase has thousands of lines of unstructured global CSS with chained selectors (.page .content .widget h2 a), a full rewrite is rarely feasible. Use the strangler fig pattern:

Micro-Frontend or Multi-Team CSS

When multiple teams contribute CSS to a single rendered page, CSS architecture becomes a coordination problem:

Dark Mode and Theming System Implementation

Dark mode implemented with CSS architecture requires deliberate token design, not ad hoc overrides:

Performance-Critical Applications (Core Web Vitals Focus)

In applications where CSS is on the LCP critical path:

Design Token Migration from Sass Variables to CSS Custom Properties

When migrating from $sass-variables to --css-custom-properties:

Third-Party CSS Integration (Component Libraries, Bootstrap, MUI)

When integrating a third-party CSS framework into an existing architecture:


Example

Input: "We're building a SaaS dashboard product with a team of 8 frontend engineers. We're using React with TypeScript and Next.js (App Router). We have a Figma design system with defined color, spacing, and typography tokens. Currently our CSS is a mess -- a mix of Bootstrap 4 overrides, some CSS Modules, and inline styles scattered everywhere. We need to get this under control. What architecture do you recommend?"


Output:

CSS Architecture Assessment

Project Profile


Recommended Architecture

| Dimension | Recommendation | Rationale |

|----------------------|---------------------------------------|---------------------------------------------------------------------------|

| Methodology | CSS Modules + ITCSS for globals | React component model maps naturally to Modules; global styles need ITCSS layers |

| Token system | CSS custom properties (3-tier) | Maps directly from Figma tokens; enables dark mode and theming natively |

| Tooling | PostCSS + Stylelint + CSS Modules | Next.js has native PostCSS and CSS Modules support -- zero additional config |

| Specificity strategy | @layer for Bootstrap isolation | Traps Bootstrap 4 CSS inside a low-priority layer; new code always wins |

| File structure | Co-located modules + global styles/ | Components own their styles; global tokens/reset live in styles/ |

| Bootstrap exit plan | Phased removal over 6--8 weeks | Remove component-by-component as each is replaced; never rewrite all at once |


Implementation Plan

Phase 1: Foundation (Week 1)

Step 1: Establish the token file from Figma.

Create styles/tokens.css and map the Figma token library to three tiers:

/* styles/tokens.css */

/* ─── Tier 1: Primitive Tokens ─────────────────────── */
:root {
  /* Color palette */
  --color-blue-50:  #eff6ff;
  --color-blue-500: #3b82f6;
  --color-blue-600: #2563eb;
  --color-blue-700: #1d4ed8;
  --color-gray-50:  #f9fafb;
  --color-gray-100: #f3f4f6;
  --color-gray-200: #e5e7eb;
  --color-gray-700: #374151;
  --color-gray-900: #111827;
  --color-white:    #ffffff;
  --color-red-500:  #ef4444;
  --color-green-500: #22c55e;

  /* Spacing scale (4px base) */
  --space-1: 0.25rem;  /* 4px  */
  --space-2: 0.5rem;   /* 8px  */
  --space-3: 0.75rem;  /* 12px */
  --space-4: 1rem;     /* 16px */
  --space-6: 1.5rem;   /* 24px */
  --space-8: 2rem;     /* 32px */
  --space-12: 3rem;    /* 48px */
  --space-16: 4rem;    /* 64px */

  /* Typography */
  --font-family-sans: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
  --font-family-mono: 'JetBrains Mono', 'Fira Code', monospace;
  --font-size-xs:   0.75rem;   /* 12px */
  --font-size-sm:   0.875rem;  /* 14px */
  --font-size-base: 1rem;      /* 16px */
  --font-size-lg:   1.125rem;  /* 18px */
  --font-size-xl:   1.25rem;   /* 20px */
  --font-size-2xl:  1.5rem;    /* 24px */
  --font-size-3xl:  1.875rem;  /* 30px */
  --font-weight-normal:   400;
  --font-weight-medium:   500;
  --font-weight-semibold: 600;
  --font-weight-bold:     700;
  --line-height-tight:  1.25;
  --line-height-normal: 1.5;
  --line-height-relaxed: 1.625;

  /* Border radius */
  --radius-sm:   0.25rem;
  --radius-md:   0.375rem;
  --radius-lg:   0.5rem;
  --radius-full: 9999px;

  /* Shadows */
  --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
  --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
  --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);

  /* Transitions */
  --transition-fast:   150ms ease;
  --transition-normal: 250ms ease;
  --transition-slow:   350ms ease;
}

/* ─── Tier 2: Semantic Tokens ───────────────────────── */
:root {
  /* Brand */
  --color-brand-primary:   var(--color-blue-500);
  --color-brand-hover:     var(--color-blue-600);
  --color-brand-active:    var(--color-blue-700);

  /* Surfaces */
  --color-surface-page:      var(--color-gray-50);
  --color-surface-card:      var(--color-white);
  --color-surface-overlay:   var(--color-white);

  /* Text */
  --color-text-primary:   var(--color-gray-900);
  --color-text-secondary: var(--color-gray-700);
  --color-text-on-brand:  var(--color-white);
  --color-text-disabled:  var(--color-gray-200);

  /* Borders */
  --color-border-default: var(--color-gray-200);
  --color-border-focus:   var(--color-blue-500);

  /* Status */
  --color-status-error:   var(--color-red-500);
  --color-status-success: var(--color-green-500);

  /* Component spacing */
  --space-section-gap:    var(--space-12);
  --space-component-gap:  var(--space-6);
  --space-element-gap:    var(--space-4);
}

/* ─── Dark Mode: Semantic Token Overrides ───────────── */
@media (prefers-color-scheme: dark) {
  :root {
    --color-surface-page:      #0f172a;
    --color-surface-card:      #1e293b;
    --color-text-primary:      #f8fafc;
    --color-text-secondary:    #94a3b8;
    --color-border-default:    #334155;
  }
}

/* User-controlled theme override (higher priority than media query) */
[data-theme="dark"] {
  --color-surface-page:   #0f172a;
  --color-surface-card:   #1e293b;
  --color-text-primary:   #f8fafc;
  --color-text-secondary: #94a3b8;
  --color-border-default: #334155;
}

Step 2: Set up global layer declarations and Bootstrap isolation.

Create styles/layers.css as the first import in your global entry:

/* styles/layers.css -- declare all layers here, in priority order */
@layer reset, bootstrap, base, components, utilities;

Create styles/bootstrap-isolated.css:

@layer bootstrap {
  @import 'bootstrap/dist/css/bootstrap.min.css';
}

Now all Bootstrap styles have the lowest priority. Any style outside a layer, or in a higher-declared layer, will override Bootstrap without !important.

Step 3: Write the global reset.

/* styles/reset.css */
@layer reset {
  *, *::before, *::after {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
  }

  html {
    font-size: 100%; /* Respect user browser font size preferences */
    -webkit-text-size-adjust: 100%;
    text-size-adjust: 100%;
  }

  body {
    font-family: var(--font-family-sans);
    font-size: var(--font-size-base);
    line-height: var(--line-height-normal);
    color: var(--color-text-primary);
    background-color: var(--color-surface-page);
  }

  img, video, svg {
    display: block;
    max-width: 100%;
  }

  button, input, select, textarea {
    font: inherit;
  }
}

Step 4: Configure the global styles/ directory.

styles/
├── layers.css          # @layer declarations (import first)
├── tokens.css          # CSS custom properties (all three tiers)
├── reset.css           # box-sizing, margin/padding reset
├── typography.css      # h1–h6 base styles using tokens
└── globals.css         # Master import file
/* styles/globals.css -- imported once in app/layout.tsx */
@import './layers.css';
@import './tokens.css';
@import './reset.css';
@import './typography.css';
@import './bootstrap-isolated.css'; /* Bootstrap inside @layer bootstrap */

In app/layout.tsx:

import '@/styles/globals.css';

Phase 2: Component Migration (Weeks 2--4)

Step 5: Establish the CSS Modules pattern for components.

Every new or refactored component gets a .module.css file. Component tokens are defined as local custom properties on the component's root selector:

/* components/Button/Button.module.css */

/* ─── Component Tokens (Tier 3) ────────────────────── */
.button {
  /* Override these to create variants */
  --button-bg:            var(--color-brand-primary);
  --button-bg-hover:      var(--color-brand-hover);
  --button-bg-active:     var(--color-brand-active);
  --button-color:         var(--color-text-on-brand);
  --button-border:        transparent;
  --button-padding-y:     var(--space-2);
  --button-padding-x:     var(--space-4);
  --button-font-size:     var(--font-size-sm);
  --button-font-weight:   var(--font-weight-medium);
  --button-radius:        var(--radius-md);
  --button-shadow:        var(--shadow-sm);
  --button-transition:    var(--transition-fast);

  /* ─── Composition ─── */
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: var(--space-2);
  padding: var(--button-padding-y) var(--button-padding-x);
  background-color: var(--button-bg);
  color: var(--button-color);
  border: 1px solid var(--button-border);
  border-radius: var(--button-radius);
  font-size: var(--button-font-size);
  font-weight: var(--button-font-weight);
  line-height: var(--line-height-tight);
  box-shadow: var(--button-shadow);
  cursor: pointer;
  transition:
    background-color var(--button-transition),
    box-shadow var(--button-transition),
    opacity var(--button-transition);
  text-decoration: none;
  white-space: nowrap;
  user-select: none;
}

.button:hover:not(:disabled) {
  --button-bg: var(--button-bg-hover);
}

.button:active:not(:disabled) {
  --button-bg: var(--button-bg-active);
  --button-shadow: none;
}

.button:focus-visible {
  outline: 2px solid var(--color-border-focus);
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* ─── Variants via Component Token Override ─────────── */
.secondary {
  --button-bg:        transparent;
  --button-bg-hover:  var(--color-gray-100);
  --button-bg-active: var(--color-gray-200);
  --button-color:     var(--color-text-primary);
  --button-border:    var(--color-border-default);
  --button-shadow:    none;
}

.ghost {
  --button-bg:        transparent;
  --button-bg-hover:  var(--color-gray-100);
  --button-bg-active: var(--color-gray-200);
  --button-color:     var(--color-brand-primary);
  --button-border:    transparent;
  --button-shadow:    none;
}

.destructive {
  --button-bg:       var(--color-status-error);
  --button-bg-hover: #dc2626;
}

/* ─── Sizes ─────────────────────────────────────────── */
.sm {
  --button-padding-y:  var(--space-1);
  --button-padding-x:  var(--space-3);
  --button-font-size:  var(--font-size-xs);
  --button-radius:     var(--radius-sm);
}

.lg {
  --button-padding-y:  var(--space-3);
  --button-padding-x:  var(--space-6);
  --button-font-size:  var(--font-size-base);
  --button-radius:     var(--radius-lg);
}
// components/Button/Button.tsx
import styles from './Button.module.css';
import clsx from 'clsx';

type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'destructive';
type ButtonSize = 'sm' | 'md' | 'lg';

interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: ButtonVariant;
  size?: ButtonSize;
}

export function Button({
  variant = 'primary',
  size = 'md',
  className,
  children,
  ...props
}: ButtonProps) {
  return (
    <button
      className={clsx(
        styles.button,
        variant !== 'primary' && styles[variant],
        size !== 'md' && styles[size],
        className
      )}
      {...props}
    >
      {children}
    </button>
  );
}

Note on the variant pattern: Using CSS custom property overrides within the module (rather than separate rule blocks per variant) keeps all color logic in one place and makes theming trivial. The dark mode override in :root automatically propagates through the token chain without any variant-level changes.


Phase 3: Tooling and Enforcement (Week 2, run alongside Phase 2)

Step 6: Configure Stylelint.

// .stylelintrc.js
module.exports = {
  extends: [
    'stylelint-config-standard',
    'stylelint-config-css-modules',
  ],
  plugins: [
    'stylelint-order',
  ],
  rules: {
    // Property declaration order
    'order/properties-order': [
      'content',
      // Positioning
      'position', 'top', 'right', 'bottom', 'left', 'z-index',
      // Display and box model
      'display', 'flex', 'flex-direction', 'flex-wrap',
      'align-items', 'justify-content', 'gap',
      'grid-template-columns', 'grid-template-rows',
      'width', 'min-width', 'max-width',
      'height', 'min-height', 'max-height',
      'padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
      'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
      'overflow',
      // Visual
      'background', 'background-color', 'background-image',
      'border', 'border-radius',
      'box-shadow',
      'opacity',
      // Typography
      'font-family', 'font-size', 'font-weight', 'line-height',
      'color', 'text-align', 'text-decoration', 'white-space',
      // Interaction
      'cursor', 'pointer-events', 'user-select',
      // Animation
      'transition', 'animation',
    ],

    // Enforce custom property usage
    'color-no-invalid-hex': true,
    'declaration-no-important': [true, {
      severity: 'warning', // Error in component files; warning for utilities
    }],
    'selector-max-id': 0,              // No ID selectors in stylesheets
    'selector-max-specificity': '0,2,0', // Flag anything exceeding 2 classes
    'selector-max-type': [2, {         // Allow element selectors only in reset/base layers
      ignoreTypes: ['html', 'body'],
    }],
    'max-nesting-depth': 1,            // Only 1 level of nesting allowed
    'custom-property-no-missing-var-function': true,
    'color-named': 'never',            // Never use color names like 'red', 'blue'
    'number-max-precision': 4,
    'unit-allowed-list': [             // Prevent arbitrary unit usage
      'rem', 'em', 'px', '%', 'vw', 'vh', 'svh', 'fr', 'deg', 'ms', 's', 'ch',
    ],
  },
  overrides: [
    {
      files: ['**/styles/reset.css', '**/styles/typography.css'],
      rules: {
        'selector-max-type': null, // Element selectors allowed in base files
      },
    },
    {
      files: ['**/styles/utilities.css'],
      rules: {
        'declaration-no-important': null, // !important is permitted in utilities
      },
    },
  ],
};

Add to package.json scripts:

{
  "scripts": {
    "lint:css": "stylelint '**/*.{css,module.css}' --allow-empty-input",
    "lint:css:fix": "stylelint '**/*.{css,module.css}' --fix"
  }
}

Add to CI pipeline (GitHub Actions example):

- name: Lint CSS
  run: npm run lint:css

Critical Decisions and Trade-offs

  1. CSS Modules over CSS-in-JS: Vanilla Extract or Emotion would also work for this React/TypeScript stack. CSS Modules was chosen because it has zero runtime cost, native Next.js support without configuration, and lower cognitive overhead for a team that already uses it inconsistently. Emotion was rejected because its SSR setup adds complexity and it has a ~7KB runtime bundle cost. Vanilla Extract was considered but the team's CSS-in-TypeScript learning curve was deemed higher risk given the timeline.
  1. @layer for Bootstrap isolation over a complete removal: Removing Bootstrap 4 immediately would require rewriting all 40+ components that use its grid, form, and utility classes. The @layer approach allows the team to remove Bootstrap incrementally over 6--8 weeks as components are replaced, while the new architecture takes effect immediately for all new code.
  1. CSS custom properties over Sass variables for tokens: Sass variables are compile-time constants and do not work for runtime theming (dark mode, user preference). CSS custom properties are runtime values, enabling dark mode via a single [data-theme] attribute change. The trade-off: custom properties cannot be used inside @media queries (breakpoints still require Sass variables or @custom-media).
  1. 3-tier token structure over flat tokens: A flat token structure (--blue-button-background: #3b82f6) is simpler initially but requires duplicating values across components and makes global changes (brand color update) require touching every component. The 3-tier structure requires more upfront design but makes global changes single-touch.

Maintenance Guidelines

These are enforced conventions. Violations must be caught in code review or by Stylelint:

  1. All new components must have a .module.css file. No new styles may be added to globals.css except tokens and base element styles.
  2. Every color, spacing, and font value in a .module.css file must reference a CSS custom property. No raw hex codes, pixel values for spacing, or hardcoded font families.
  3. Bootstrap classes must not be added to any new component. If a Bootstrap utility is needed, use the equivalent semantic token or add a utility class to styles/utilities.css.
  4. The styles/tokens.css file is the single source of truth for design values. If Figma updates a token, update tokens.css first, then verify all components that use that token render correctly.
  5. PR checklist item: "Does this component introduce any magic number values?" is required on every CSS-related PR.
  6. Run npm run lint:css before every PR. The CI check is non-negotiable and will block merges.
  7. Component tokens (Tier 3) defined in .module.css files must not be referenced by other component files. They are local to that component. Cross-component token dependencies must be elevated to Tier 2 in tokens.css.
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.