Modular CSS: Components, Variants, Naming Conventions and BEM
Organizing CSS into independent, reusable modules: one class per module, modifier classes for variants, BEM block, element and modifier names, styling state through attributes, composing modules without coupling, and names that survive redesigns.
kvi5hnuCode Sprout team member8 min readOn this page
A small stylesheet can be a list of rules. A large one, worked on by several people for years, falls apart that way: rules for one part of the page leak into another, selectors get longer and more specific to win, and nobody dares delete anything. Modular CSS prevents this by splitting the interface into independent pieces, modules or components, each with its own styles that work anywhere on the page and never depend on, or change, another module.
A module
A module is identified by one class on its outermost element, and its rules start from that class:
.message {
padding: 0.8em 1.2em;
border: 1px solid #1d6f7a;
border-radius: 0.3em;
background: #e3f4f6;
color: #10424a;
}
<div class="message">Your changes were saved.</div>
The selector is just .message. It doesn't say where the message is, like #sidebar .message would, so it works in a form, a dialog or a sidebar, and looks the same everywhere. Repeated, slightly different copies of the same component, like .save-form button, .login-form button and .toolbar .options, drift apart over time; one module stays consistent.
Global styles, like the reset, base typography and link colors, come before the modules. Article 117 organizes them into layers.
Variants: modifier classes
When a module needs to look different in some situations, add a modifier class to the same element, named after the module:
.message--error { border-color: #a12a2a; background: #fbe9e9; color: #5c1515; }
.message--success { border-color: #2f7d32; background: #e8f5e9; color: #1b4a1d; }
<div class="message message--error">The email address is invalid.</div>
The modifier only states what's different, and has the same specificity as the base class, so it must come after it in the stylesheet.
Never change a module based on where it is, as in .page-header .dropdown { … }:
- the rule belongs neither to the header nor to the dropdown, so it's hard to find;
- it raises specificity, so the next change needs an even stronger selector;
- it can't be reused: a dark dropdown in the sidebar needs another selector;
- it ties the CSS to one HTML structure.
Write a modifier instead, .dropdown--dark, and put it where it's needed. That single rule prevents most stylesheet decay.

The graphs compare two stylesheets for the same interface. With location-based selectors, specificity jumps around and reaches 1,3,0, so any later fix needs an ID or !important to win. With one class per module, it stays almost flat, and source order or layers decide conflicts predictably.

The location-based rule silently misses the sidebar copy, and fixing that means yet another selector. The modifier works in both places because the dropdown carries its own variant.
Modules with several parts: BEM

Most modules have inner parts. BEM (Block, Element, Modifier) is a naming convention that shows how every class relates to its module:
| Part | Pattern | Example |
|---|---|---|
| Block | the module's name | .media |
| Element | block, __, part | .media__image, .media__body |
| Modifier | block or element, --, variant | .media--reversed, .button--small |
.media { display: flex; gap: 1rem; align-items: flex-start; }
.media__image { flex: none; inline-size: 6rem; border-radius: 0.4rem; }
.media__body { flex: 1; }
.media__body > h3 { margin-block-start: 0; }
.media--reversed { flex-direction: row-reverse; }
- Element classes are flat:
.media__image, not.media .media__image. The name already says where it belongs, and specificity stays at a single class. - Elements belong to the block, not to each other: use
.card__title, not.card__header__title, even if the title is inside the header. - A modifier on the block can adjust its elements:
.media--reversed .media__image { … }. That's the one acceptable descendant selector, since it stays within the module. - Targeting a child by tag, like
.media__body > h3or.menu > li, is fine for specific elements. Avoid generic ones likedivandspan, which may later appear in the module for another purpose. - Native CSS nesting can't build BEM names:
&__imageis invalid (article 21). Write.media__imagein full, or nest& .media__imageif you want grouping.
State
States set by JavaScript or by the user are different from design variants. Common conventions:
.dropdown__drawer { display: none; }
.dropdown.is-open .dropdown__drawer { display: block; } /* a state class */
Better still, style the state that already exists in the HTML, which also keeps accessibility attributes and visuals in sync:
.dropdown__toggle[aria-expanded="true"] + .dropdown__drawer { display: block; }
.tab[aria-selected="true"] { border-block-end-color: currentColor; }
details[open] > summary::after { rotate: 90deg; }
input:user-invalid { border-color: #a12a2a; }
Attribute and pseudo-class states (articles 8 and 11) can't fall out of sync with what assistive technology announces, as a separate is-open class can.
Composing modules
Each module should do one thing. If describing it needs "and", as in "a dropdown that shows a list of links and styles each link", consider two modules. Here, dropdown is responsible for the toggle and showing or hiding the drawer, and menu styles a list of links. The menu can then be reused in a sidebar, and the dropdown can hold a form instead:
<div class="dropdown">
<button class="dropdown__toggle" aria-expanded="false">Account</button>
<div class="dropdown__drawer">
<ul class="menu">
<li><a class="menu__item" href="/profile">Profile</a></li>
<li><a class="menu__item" href="/settings">Settings</a></li>
</ul>
</div>
</div>
Neither module's CSS mentions the other. Layout around modules is usually its own concern: a separate layout module (.stack, .cluster, .grid) or utility classes (article 117) set spacing between modules, so a module doesn't set its own outer margin and spacing stays consistent.
Naming modules
- Name modules by what they are, not their content or appearance.
.running-tipbreaks when the same box shows upcoming races;.gray-boxbreaks when it turns blue..media,.panel,.alert,.tileand.form-controlsurvive. - Name variants by purpose:
.button--dangerand.button--secondary, not.button--red. Relative names like--largeare acceptable. - Agree on names as a team, so "use a media here" means the same to everyone, and prefix them in shared libraries (
.acme-button) to avoid collisions with other code. - Some teams require two-word module names, like
.product-tile, to leave room for future modules.
Other ways to scope styles
Naming conventions depend on discipline. Several tools enforce scoping instead:
@scope(article 22) limits rules to a subtree in the browser itself, with an optional lower boundary so a module's rules stop at nested modules, and without adding specificity.@scope (.media) to (.media__body > *) { img { … } }.- Cascade layers (article 20) decide which group of rules wins, regardless of specificity.
- Shadow DOM (article 14) fully isolates a web component's styles.
- CSS Modules and CSS-in-JS libraries generate unique class names at build time, for JavaScript-rendered applications. They tie styling to a build tool or framework.
:where()(article 12) keeps selectors at zero specificity, so modules are easy to override.
These complement modular thinking rather than replace it: you still need small, single-purpose modules with clear names.
body { font: 0.85rem/1.4 system-ui, sans-serif; margin: 1rem; color: #2a2118; }
/* layout module: spacing between modules */
.stack > * + * { margin-block-start: 0.7rem; }
/* message */
.message { padding: 0.5em 0.8em; border: 1px solid #1d6f7a; border-radius: 0.3em; background: #e3f4f6; color: #10424a; }
.message--error { border-color: #a12a2a; background: #fbe9e9; color: #5c1515; }
/* media */
.media { display: flex; gap: 0.8rem; align-items: flex-start; }
.media__image { flex: none; inline-size: 3.5rem; aspect-ratio: 1; border-radius: 0.4rem; background: linear-gradient(135deg, #8a3b12, #f4c95d); }
.media__body { flex: 1; }
.media__body > h3 { margin: 0; font-size: 1rem; }
.media__body > p { margin: 0.2rem 0 0; }
.media--reversed { flex-direction: row-reverse; }
/* dropdown: only showing and hiding */
.dropdown { position: relative; display: inline-block; }
.dropdown__toggle { font: inherit; padding: 0.4em 0.8em; border: 0; border-radius: 0.3em; background: #1d3557; color: white; }
.dropdown__drawer { display: none; position: absolute; inset-block-start: 100%; inset-inline-start: 0; margin-block-start: 0.3rem; }
.dropdown__toggle[aria-expanded="true"] + .dropdown__drawer { display: block; }
/* menu: only the list of links; knows nothing about dropdowns */
.menu { list-style: none; margin: 0; padding: 0.3rem; min-inline-size: 9rem; border: 1px solid #d8cfc0; border-radius: 0.4rem; background: white; box-shadow: 0 6px 16px rgb(0 0 0 / 0.12); }
.menu__item { display: block; padding: 0.35em 0.6em; border-radius: 0.3em; color: inherit; text-decoration: none; }
.menu__item:is(:hover, :focus-visible) { background: #f4efe6; }
Each module's rules start with its own class. The modifiers change only what differs, the dropdown opens from the aria-expanded state the script already sets for screen readers, and the menu inside has no idea it's in a dropdown. The .stack layout module handles the spacing between them.
What's current
- BEM and similar conventions remain widely used;
@scope(all browsers since Firefox 146) and cascade layers reduce how much they need to carry. - Native nesting doesn't concatenate names, so BEM classes are written in full.
Common questions
Do I have to use BEM? No. Any consistent convention works. What matters is one class per module, flat selectors, and modifiers instead of location-based overrides.
Isn't class="media media--reversed" repetitive?
Slightly, but it keeps the base styles in one place and makes the variant explicit. Some teams use attributes instead: <div class="media" data-variant="reversed">.
Where do margins between modules go? On a layout module or utility, not on the modules themselves, so they fit in any context.
When should I split a module? When its description needs "and", or when part of it would be useful on its own.
Summary
- A module is one class plus its parts; its styles work anywhere and don't touch other modules.
- Variants are modifier classes; never restyle a module by its location.
- BEM names show structure:
block,block__element,block--modifier, kept flat. - Style state through attributes and pseudo-classes when possible.
- Give each module one responsibility and a name that describes what it is, not how it looks.
Practice questions
Rewrite this rule in a modular way.
#sidebar .widget h2 { color: white; background: #1d3557; }
Answer
Give the heading, or the widget, a class of its own and a modifier for the dark version, independent of the sidebar:
.widget__title { font-size: 1.1rem; }
.widget--dark .widget__title { color: white; background: #1d3557; }
Then use <section class="widget widget--dark"> wherever a dark widget is needed.
Name the BEM classes for a card with an image, a title, a footer and a "featured" variant.
Answer
.card, .card__image, .card__title, .card__footer and .card--featured.
Why is .button--blue a poor modifier name?
Answer
It describes appearance, which changes in redesigns. If the brand color becomes green, the name is wrong. Name it by purpose, such as .button--primary.
Why might .dropdown.is-open be worse than [aria-expanded="true"] for styling an open dropdown?
Answer
A separate class can get out of sync with the ARIA attribute that screen readers use. Styling the attribute means the visual state and the announced state always match, with one thing for the script to update.
Previous: Scroll Snap and CSS Carousels: scroll-snap-type, ::scroll-button and ::scroll-marker
Next: Organizing a Stylesheet With Layers: Reset, Theme, Layout, Components and Utilities

More in CSS Course
Quiz: CSS Delicate Details
Twenty-five questions on the edge cases that surprise experienced developers: invalid custom properties, shorthands that reset values, layer order with !important, containing blocks, margin collapsing, specificity of :is() and :where(), intrinsic minimum sizes, and more, each checked in Chrome.
Quiz: CSS Interview Questions
Thirty front-end interview questions: cascade, specificity and layers, box model and margin collapsing, stacking contexts, positioning, flexbox and grid, responsive design, custom properties, performance, accessibility, modern selectors and architecture.
Quiz: CSS Course Final Exam
Thirty questions across the whole CSS course: syntax and error handling, selectors, the cascade and layers, values and units, color, the box model, backgrounds, positioning, flexbox, grid, responsive design, typography, generated content, effects, transforms, motion and architecture.
Quiz: CSS Architecture, Tooling and Debugging (CSS Part 17)
Twenty questions on modular CSS and BEM, layering a stylesheet, design tokens and theming, pattern libraries and safe refactoring, preprocessors and build tools, the at-rules reference, and debugging common CSS problems.
Discussion
Sign in to ask a question or share what you learned.