Chapter 32 of 33

CSS Architecture & BEM

Writing CSS for one page is easy. Writing CSS for a website with fifty pages, five developers and two years of changes is a different problem. The language features are the same — the hard part is organisation.

In this chapter we look at why CSS becomes messy as projects grow, the principles that keep it under control, and the most popular naming method in the industry: BEM (Block, Element, Modifier). We also compare BEM with other approaches (OOCSS, SMACSS, ITCSS, utility-first) and finish with cascade layers, a built-in CSS feature for organising style sheets.

This chapter builds on CSS Selectors and Specificity, Inheritance & the Cascade, and refers back to nesting from Modern CSS: :has(), Nesting, clamp() & Logical Properties.


Why CSS Gets Messy

Imagine a college fest website. Week 1, someone writes:

.title {
  font-size: 32px;
  color: navy;
}

Week 6, someone else adds an events section and also needs a "title", but smaller:

.events .title {
  font-size: 20px;
}

Week 10, the sponsors box inside the events section needs its title to be big again:

#sponsors .events .title {
  font-size: 28px !important;
}

This is how a specificity war starts. Each fix needs a stronger selector than the last, until someone reaches for !important. The root causes are built into CSS itself:

ProblemWhat happens
Global scopeEvery class name is visible to every page. Two developers who both write .title affect each other.
Specificity battlesLong selectors and IDs make rules hard to override, so people write even longer selectors.
Coupling to HTML structure.sidebar div ul li a breaks as soon as someone wraps the list in another element.
Fear of deletingNobody knows which pages use .box2, so nobody deletes it. The file only grows.
Unclear names.red, .left-box, .new-style-final say nothing about purpose.

CSS architecture is a set of conventions for naming, structuring and ordering style sheets so that styles are predictable, reusable and safe to change as a project grows.


Principles of Maintainable CSS

Almost every methodology is built on the same few ideas:

  1. Keep specificity low and flat. If most selectors are a single class (0,1,0), then the rule that comes later wins, which is easy to reason about. Avoid IDs and long descendant chains for styling.

  2. Style with classes, not tags or structure. .menu__link keeps working whether the link is inside a ul, a div or a nav.

  3. Think in components. A card, a button, a navbar — each is a self-contained unit that can be dropped anywhere.

  4. Single responsibility. One class does one job. A button class shouldn't also decide where the button sits on the page.

  5. Names describe purpose, not appearance. .alert--error survives a redesign; .red-text becomes a lie when the brand colour changes to orange.

  6. Predictable order. Generic styles first, specific styles last.


BEM: Block, Element, Modifier

BEM is a naming methodology created at the Russian company Yandex. Its idea is simple: a class name should tell you which component it belongs to, which part of that component it is, and which variation it represents.

TermMeaningExample class
BlockA standalone, reusable component that makes sense on its owncard, menu, button, search-form
ElementA part of a block that has no meaning outside that blockcard__title, menu__item, search-form__input
ModifierA flag that changes the look, state or behaviour of a block or elementcard--featured, menu__item--active, button--large

The naming pattern

block__element--modifier
  │      │          │
  │      │          └── two hyphens (--) introduce a modifier
  │      └──────────── two underscores (__) introduce an element
  └─────────────────── block name: lowercase words joined by single hyphens

card                      → block
card__title               → element "title" of block "card"
card--featured            → modifier "featured" of block "card"
card__button--disabled    → modifier "disabled" of element "button" of block "card"
search-form__input        → multi-word block name uses a single hyphen

The double separators exist so you can tell the parts apart even when names contain hyphens: in search-form__submit-button, the block is clearly search-form and the element is clearly submit-button.

The style above (-- for modifiers) is the one most teams use. The official BEM documentation calls it the "two dashes" style; its "classic" style uses a single underscore for modifiers instead, like menu__item_visible or button_size_large. Both are valid BEM — what matters is that a project picks one and sticks to it.

A complete BEM example

<article class="card">
  <img class="card__image" src="dsa.jpg" alt="">
  <h3 class="card__title">Data Structures Notes</h3>
  <p class="card__text">Arrays, stacks, queues and trees explained.</p>
  <button class="card__button">Read more</button>
</article>

<article class="card card--featured">
  <img class="card__image" src="gate.jpg" alt="">
  <h3 class="card__title">GATE CS Roadmap</h3>
  <p class="card__text">A 6-month plan for GATE preparation.</p>
  <button class="card__button card__button--disabled">Coming soon</button>
</article>
/* Block */
.card {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  max-width: 18rem;
  padding: 1rem;
  border: 1px solid #ddd;
  border-radius: 8px;
}

/* Elements */
.card__image {
  width: 100%;
  aspect-ratio: 16 / 9;
  object-fit: cover;
  border-radius: 4px;
}

.card__title {
  margin: 0;
  font-size: 1.25rem;
}

.card__text {
  margin: 0;
  color: #555;
}

.card__button {
  align-self: start;
  padding: 0.5rem 1rem;
  border: 0;
  border-radius: 4px;
  background: #2563eb;
  color: white;
}

/* Modifiers */
.card--featured {
  border-color: #f59e0b;
  box-shadow: 0 0 0 3px #fde68a;
}

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

Output: two cards, one below the other (each article is a block, and nothing here places them in a row). Both have the same layout — image, bold title, grey text, blue button. The second card has an amber border with a soft yellow glow (from card--featured), and its "Coming soon" button is faded (from card__button--disabled).

Look at the selectors: every one of them is a single class. Their specificity is all (0,1,0). The modifier wins over the base style simply because it comes later in the file — no IDs, no nesting, no !important.

Why BEM works

  • No accidental collisions. .card__title and .modal__title can never clash, unlike two developers' .title.

  • Flat specificity. Overriding is predictable.

  • Self-documenting HTML. Reading class="card__button--disabled", you know where its CSS lives and what it does.

  • Safe to move and delete. The card's styles don't depend on where the card sits. Searching for card__ finds every part of it; if the block is gone from the HTML, all of its CSS can go too.


BEM Rules That Beginners Break

Rule 1: Elements belong to the block, not to other elements

Even if the title is inside a header inside the card, its name stays flat:

<article class="card">
  <header class="card__header">
    <h3 class="card__title">...</h3>          <!-- ✅ -->
    <h3 class="card__header__title">...</h3>  <!-- ❌ -->
  </header>
</article>

Names describe ownership, not the HTML tree. If you later move the title out of the header, card__title is still correct; card__header__title becomes wrong.

Rule 2: A modifier is used together with its base class

<article class="card card--featured">   <!-- ✅ base + modifier -->
<article class="card--featured">        <!-- ❌ loses all the .card styles -->

The modifier only contains the differences. The base class provides everything else.

Rule 3: Don't style by tag or by nesting inside a block

.card h3 { ... }        /* ❌ breaks if the title becomes an h2 */
.card .card__title { }  /* ❌ unnecessary, doubles the specificity */
.card__title { ... }    /* ✅ */

Rule 4: Blocks shouldn't position themselves

A block should look right wherever it is placed. Outer margins, widths in a grid and positions are decided by the parent. BEM handles this with a mix: one HTML element carrying classes from two blocks.

<!-- the button is a reusable "button" block AND an element of the "card" -->
<button class="button button--primary card__button">Read more</button>
.button { padding: 0.5rem 1rem; border-radius: 4px; }  /* how it looks */
.card__button { align-self: start; }                   /* where it sits in a card */

Rule 5: Modifiers describe a variation, not a value

button--large and alert--error are good. button--padding-20px and text--red describe appearance and will break when the design changes.


BEM with Nesting

In Modern CSS: :has(), Nesting, clamp() & Logical Properties we saw that native CSS & is not string concatenation. So this Sass-style shortcut does not work in plain CSS:

/* Sass only — in native CSS the &__title rule is silently dropped */
.card {
  &__title { font-size: 1.25rem; }
  &--featured { border-color: #f59e0b; }
}

In plain CSS, write BEM classes flat (as in the example above). Nesting is still useful for states and media queries on a single class, which keeps specificity low:

.card__button {
  background: #2563eb;

  &:hover {
    background: #1d4ed8;          /* .card__button:hover */
  }

  @media (width < 480px) {
    width: 100%;
  }
}

State Classes

Some states are toggled by JavaScript: a menu opening, a tab being selected. Many teams use a separate is- or has- prefix for these (an idea from SMACSS, below):

.menu.is-open { display: block; }
.tab.is-active { border-bottom-color: currentColor; }

Pure BEM would write menu--open instead. Either is fine; the is- prefix makes it obvious that a script changes the class at runtime. Prefer native states when they exist — :checked, :disabled, [aria-expanded="true"] — so the CSS and the accessibility information never disagree.


Other Methodologies

BEM is about naming. Other methodologies focus on how to split and how to order CSS. They are often combined.

OOCSS (Object-Oriented CSS)

Proposed by Nicole Sullivan. Two main principles:

  • Separate structure from skin: layout properties (width, padding) in one class, visual "skin" (colours, shadows) in another, so skins can be reused.

  • Separate container from content: a heading should look the same whether it is in the sidebar or the footer — no .sidebar h3.

The famous example is the "media object" (an image on the left, text on the right), defined once as a reusable .media class.

SMACSS (Scalable and Modular Architecture for CSS)

By Jonathan Snook. It sorts rules into five categories:

CategoryContainsExample
BaseDefaults for bare elementsbody, a, h1
LayoutMajor page sections.l-header, .l-sidebar
ModuleReusable components.card, .navbar
StateHow things look in a state.is-hidden, .is-active
ThemeAlternative look and feel.theme-dark

ITCSS (Inverted Triangle CSS)

By Harry Roberts. It orders the whole style sheet from generic, far-reaching, low-specificity rules at the top to specific, narrow, high-priority rules at the bottom:

  ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
  \  Settings   variables, no CSS output     /   reach: wide
   \ Tools      mixins/functions (Sass)      /    specificity: low
    \ Generic   resets, box-sizing          /
     \ Elements bare tags: h1, a, p        /
      \ Objects layout patterns: .o-grid  /
       \ Components .card, .navbar       /
        \ Utilities .u-hidden, .mt-0    /     reach: narrow
         \_____________________________/      specificity: high

Because each layer only overrides layers above it, you rarely fight the cascade. (The last layer was originally called "Trumps".)

Utility-first CSS

Popularised by Tailwind CSS. Instead of writing component classes, you compose many tiny single-purpose classes directly in the HTML:

<article class="flex flex-col gap-2 p-4 border rounded-lg">...</article>

No naming decisions and no growing CSS file — but long class attributes, and repeated patterns must be extracted into components in your templating framework.

Scoped CSS

Tools such as CSS Modules, Vue's scoped styles or CSS-in-JS libraries automatically rewrite class names (for example .title → .title_x7f2a) so they cannot clash. They solve the global-scope problem with tooling instead of naming discipline.

Comparison

ApproachMain ideaStrengthWeakness
BEMStrict naming: block__element--modifierClear, flat, no tools neededLong class names
OOCSSReusable "objects", structure vs skinVery reusable CSSHTML gets many classes
SMACSSFive categories of rulesClear file organisationNaming left loose
ITCSSOrder by specificity and reachCascade works for youNeeds discipline in where code goes
Utility-firstTiny single-purpose classes in HTMLFast to build, small CSSCluttered markup
Scoped CSSTooling generates unique namesCollisions impossibleNeeds a build step/framework

A very common real-world combo: ITCSS-style file order + BEM names for components + a few utilities.


Cascade Layers (@layer)

ITCSS orders code by convention. Modern CSS gives us a way to make that order official: cascade layers, supported in all major browsers since March 2022.

@layer groups rules into named layers. When two normal declarations conflict, the one in the later-declared layer wins, no matter how specific the other selector is. Specificity and source order only decide ties inside the same layer. Styles that are not in any layer beat all layered styles.

/* 1. declare the order once, at the top: first = weakest */
@layer reset, base, components, utilities;

/* 2. put rules into layers (in any order, even in different files) */
@layer utilities {
  .mt-0 { margin-top: 0; }
}

@layer components {
  .card { margin-top: 20px; }
}

@layer base {
  #x p { color: red; }
}

/* 3. unlayered rule */
.unlayered { color: green; }
<article class="card mt-0">...</article>

<div id="x">
  <p class="unlayered">Which colour?</p>
</div>

Results (checked in Chrome):

  • The card's top margin is 0px. .mt-0 and .card have the same specificity, and .mt-0 even appears earlier in the file — but utilities was declared after components, so it wins.

  • The paragraph is green. #x p has specificity (1,0,1), far higher than .unlayered at (0,1,0) — but unlayered styles beat layered ones.

How the cascade decides between two normal declarations (simplified):

1. Origin / importance    (author vs browser, !important)
2. Context (Shadow DOM)
3. Inline style=""        a style attribute beats any selector
4. Layer order            unlayered  >  utilities  >  components  >  base  >  reset
5. Specificity            only compared inside the same layer
6. Source order           last one wins

Note: for !important declarations the layer order is reversed — an important declaration in the first layer beats an important one in a later layer, and important declarations inside layers beat important ones outside layers. This lets a reset layer protect a few critical rules.

Layers are especially useful for third-party CSS: @import url("library.css") layer(vendor); puts a whole library into a layer named vendor. Layer order is decided by where each name first appears, so list it first (@layer vendor, base, components, utilities; before the @import) to make it the weakest layer. Then your own simple class selectors override the library without specificity tricks.


Organising Files

A typical small-to-medium project, following ITCSS order and BEM blocks:

css/
├── main.css              ← declares @layer order and imports the rest
├── settings/
│   └── tokens.css        ← :root { --color-primary: ...; --space-4: ...; }
├── generic/
│   └── reset.css         ← box-sizing, margin resets
├── elements/
│   └── base.css          ← body, headings, links, images
├── objects/
│   └── layout.css        ← .container, .stack, .grid
├── components/
│   ├── button.css        ← .button, .button--primary ...
│   ├── card.css          ← .card, .card__title ...
│   └── navbar.css
└── utilities/
    └── utilities.css     ← .visually-hidden, .text-center

One block per file is a great habit: to change the card, open card.css; to delete the card, delete card.css. (Remember from Adding CSS to HTML that many @imports cost extra requests in production, so real projects usually bundle these files with a build tool.) Design values live in custom properties, as you learned in CSS Variables (Custom Properties), so a re-brand touches one file.


Worked Example: Refactoring to BEM

Here is "before" CSS from a student project:

#profile { padding: 20px; }
#profile div img { border-radius: 50%; width: 80px; }
#profile h2 { font-size: 22px; }
#profile .small { color: gray; }
.dark #profile h2 { color: white; }

Problems: IDs (can't reuse the profile twice on a page), tag-based selectors (div img, h2), a vague class (.small), and specificities as high as (1,1,1) for .dark #profile h2.

Step 1 — identify the block and its parts: block profile; elements avatar, name, role; a dark variation.

Step 2 — rename:

<section class="profile profile--dark">
  <img class="profile__avatar" src="me.jpg" alt="Photo of Riya">
  <h2 class="profile__name">Riya Sharma</h2>
  <p class="profile__role">3rd year CSE</p>
</section>
.profile        { padding: 20px; }
.profile__avatar { width: 80px; border-radius: 50%; }
.profile__name  { font-size: 22px; }
.profile__role  { color: gray; }

.profile--dark .profile__name { color: white; }

Step 3 — compare specificity:

BeforeSpecificityAfterSpecificity
#profile div img(1,0,2).profile__avatar(0,1,0)
#profile h2(1,0,1).profile__name(0,1,0)
.dark #profile h2(1,1,1).profile--dark .profile__name(0,2,0)

The last line shows an accepted exception: when a block modifier changes an element, BEM allows the descendant selector .block--mod .block__elem. Its specificity is still only (0,2,0), and the component can now appear many times on a page, in any theme.


Common Mistakes

  • Element chains like card__body__title. Keep one level: card__title.

  • Modifier without the base class: class="button--large" alone.

  • Making everything a block, or the opposite, one giant block called page with 80 elements. A block should be a meaningful, reusable component.

  • Appearance-based names: .blue-box, .left-col.

  • Nesting BEM selectors (.card .card__title) "for safety" — it only raises specificity.

  • Using Sass-style &__element in plain CSS.

  • Reaching for !important to fix ordering problems that layers or a cleaner file order would solve.


Interview / Exam Questions

1. What do B, E and M stand for in BEM? Give one example of each.

Block: a standalone component, e.g. navbar. Element: a part of a block that only makes sense inside it, e.g. navbar__link. Modifier: a variation or state, e.g. navbar__link--active or navbar--sticky.

2. Is form__fieldset__input a correct BEM name? How would you fix it?

No. BEM elements always belong directly to the block, not to other elements, so element chains are not allowed. Use form__input (and form__fieldset for the fieldset). The name stays correct even if the HTML structure changes.

3. Why do BEM style sheets rarely need !important?

Almost all BEM selectors are a single class with specificity (0,1,0). When everything has the same specificity, the later rule wins, so modifiers simply come after their base classes. There is no specificity war to escalate.

4. With @layer base, components; declared, which wins: "@layer base { #nav a { color: red } }" or "@layer components { a { color: blue } }"?

Blue. Between layers, the later-declared layer wins for normal declarations regardless of specificity. components comes after base, so its a rule (0,0,1) beats #nav a (1,0,1).

5. What is the difference between a BEM modifier and a mix?

A modifier (button--large) is a variation of the same block or element and is used alongside its base class. A mix puts classes from different blocks on one element (class="button card__button"), so the element is both a reusable button and a part of the card; the card's element class usually handles positioning.

6. Name the layers of ITCSS from top to bottom and explain the ordering principle.

Settings, Tools, Generic, Elements, Objects, Components, Utilities (originally "Trumps"). Rules are ordered from wide reach and low specificity to narrow reach and high specificity, so each layer can override the ones above it without fighting the cascade.


Summary

  • CSS grows messy because of global scope, specificity battles and coupling to HTML structure.

  • Good architecture means: class-based, low and flat specificity, components with single responsibility, purposeful names, predictable order.

  • BEM: block, block__element, block--modifier, block__element--modifier. Elements don't chain; modifiers go with the base class; blocks don't position themselves (use mixes).

  • Native nesting can't build BEM names with &__; write classes flat and nest only states and media queries.

  • OOCSS (reuse, structure vs skin), SMACSS (five categories), ITCSS (order by specificity), utility-first and scoped CSS solve related problems in different ways.

  • @layer makes the order official: later layers beat earlier ones regardless of specificity, and unlayered styles beat all layers (reversed for !important).

In the final chapter, Project: Build a Responsive Landing Page, we put all of this together — BEM names, custom properties, Flexbox, Grid, media queries and clamp() — in one complete page.