Modular CSS divides a page into small, reusable styling units. Each module owns the styles for its elements and should work wherever it is placed, without changing another module’s appearance. This is encapsulation applied to CSS: changing one component should not unexpectedly change another. section 9.1 section 9.5
Start with resets and shared styles, such as fonts, then define modules for discrete components. Cascade layers can separate reset, global, and module rules, but layers are not required for modular CSS. section 9.1.1
A message that travels
A `.message` rule can set padding, border, and colors for a notification. Apply its class to feedback beside a form or elsewhere on the page. Avoid `#sidebar .message`: that selector makes the styling depend on a particular location. Reusing one module also prevents near-duplicate components from gradually acquiring inconsistent spacing or colors. section 9.1.2
Put variations on the module itself. For example, use `message message--error` for an error while retaining the base message styles; success and warning variants can change the same color properties. A header-specific rule such as `.page-header .dropdown` instead ties a variant to its surroundings, raises specificity, and is harder to reuse elsewhere. section 9.1.3
Listing 9.4 Message module with modifier classes
@layer modules {
.message { #1
padding: 0.8em 1.2em;
border-radius: 0.2em;
border: 1px solid #265559;
color: #265559;
background-color: #e0f0f2;
}
.message--success { #2
color: #2f5926;
border-color: #2f5926;
background-color: #cfe8c9;
}
.message--warning { #3
color: #594826;
border-color: #594826;
background-color: #e8dec9;
}
.message--error { #4
color: #59262f;
border-color: #59262f;
background-color: #e8c9cf;
}
}
The base `.message` rule holds shared styling; separate modifier classes supply success, warning, and error colors without repeating the whole module. section 9.1.3
Nested modules need boundaries too. `@scope` can restrict styles to a portion of the page; an inner scoping limit can keep them from targeting a nested module. Where nested scopes both match an element, scope proximity can let the nearer module’s rule take precedence, after specificity and before source order. Check browser support before relying on this newer feature. section 9.3.1 section 9.5
For responsive modules, define containers predictably where other modules may be nested. A content-holding module element can serve as a container, allowing children to respond to their available space through container queries rather than relying on viewport media queries. For a larger collection of modules, a pattern library can inventory what is available for assembling pages. section 10.2.3 section 9.5
