CSS Architecture and Maintainability
Design scalable stylesheets using component boundaries, naming conventions, cascade layers, utility patterns, and predictable dependency management.
Component-Oriented CSS
Component-oriented CSS organizes styles around reusable UI units rather than pages alone. A component should ideally own its structural styling while global styles establish foundations such as typography, tokens, and resets.
Good boundaries reduce accidental dependencies between unrelated components.
.card {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 1px solid var(--border-color);
}
.card__title {
margin: 0;
}
.card__actions {
display: flex;
gap: 0.75rem;
}- Keep component styles locally understandable.
- Avoid accidental dependencies on distant selectors.
What is an advantage of component-oriented CSS?
BEM Naming
BEM stands for Block, Element, Modifier. A block represents a component, an element is a meaningful child part, and a modifier represents a variation or state.
BEM is not mandatory, but its naming principles can reduce ambiguity in large stylesheets.
.card {}
.card__title {}
.card__actions {}
.card--featured {}
.card--compact {}- Blocks represent independent components.
- Elements represent component parts.
- Modifiers represent variations.
In BEM, what does `.card__title` usually represent?
Cascade Layers for Large Systems
Cascade layers provide explicit ordering between groups of CSS rules. A scalable architecture may define layers such as reset, base, components, utilities, and overrides.
This reduces the need to win specificity battles between unrelated styles.
@layer reset, base, components, utilities;
@layer reset {
*, *::before, *::after {
box-sizing: border-box;
}
}
@layer components {
.button {
padding: 0.75rem 1rem;
}
}
@layer utilities {
.hidden {
display: none !important;
}
}- Layers can control precedence without excessive selector specificity.
- Define a clear layer strategy before a project becomes difficult to restructure.
What problem can `@layer` help solve?
Resets and Base Styles
Browsers provide default user-agent styles. A CSS reset or carefully designed base layer establishes predictable defaults.
Modern resets often avoid removing useful accessibility behavior and instead focus on box sizing, margin consistency, typography inheritance, responsive media, and sensible defaults.
*,
*::before,
*::after {
box-sizing: border-box;
}
html {
line-height: 1.5;
-webkit-text-size-adjust: 100%;
}
body {
margin: 0;
}
img,
picture,
video,
canvas,
svg {
display: block;
max-width: 100%;
}- Resets should establish intentional defaults.
- Do not blindly copy large resets without understanding their consequences.
Why are CSS resets used?