Lesson 12 / 12100%

Lesson 12

CSS Organization and Best Practices

16 min

Name classes, organize stylesheets and avoid common pitfalls.

Definition

CSS organization refers to the set of conventions that structure a stylesheet: how to name classes, how to split the code into files, how to order rules, and how to limit specificity conflicts. Its goal is to keep code readable, predictable and easy to evolve, including by other people.

Why organize your CSS?

A small project can live with a single messy CSS file. But as soon as the site grows, poorly organized CSS becomes hard to maintain: duplicate classes, specificity conflicts, and the fear of changing a rule in case it breaks something else elsewhere. A few simple conventions prevent these problems.

Naming your classes: the BEM method

BEM (Block, Element, Modifier) is a very widespread naming convention that makes the role of each class explicit just by reading it.

bem.html
<div class="card">
  <img class="card__image" src="photo.jpg" alt="..." />
  <h3 class="card__title">Card title</h3>
  <p class="card__text">Description...</p>
  <button class="card__button card__button--primary">Learn more</button>
</div>
bem.css
/* Block: the component itself */
.card { padding: 20px; border-radius: 12px; }

/* Element: a sub-part of the block, with __ */
.card__image { width: 100%; border-radius: 8px; }
.card__title { font-size: 18px; font-weight: bold; }
.card__text { color: #64748b; }

/* Modifier: a variant, with -- */
.card__button--primary { background-color: #6d28d9; color: white; }
CSS best practices
  • Block — the standalone component (card).
  • Element — a part of the block, separated by __ (card__title).
  • Modifier — a variant, separated by -- (card__button--primary).

The golden rules of BEM

BEM rests on a simple idea: a single class is enough to style an element. Since each class carries its context in its name, you no longer need nested selectors, and specificity stays uniformly low. Style rules are then easy to override, and a component can be moved elsewhere without breaking its appearance.

  • An element always belongs to a block, never to another element: write card__title, not card__body__title.
  • A modifier is combined with the base class: class="card__button card__button--primary".
  • Avoid targeting a tag inside a class: .card__title rather than .card h3.
bem-bad-good.css
/* Avoid: nested selector, high specificity, depends on the HTML structure */
.page .card .body h3 span {
  color: #6d28d9;
}

/* Preferable: one class, minimal specificity, independent of the structure */
.card__label {
  color: #6d28d9;
}

Other naming approaches

BEM isn’t the only method. There are others that answer the same question — how to keep CSS predictable — with a different philosophy. Knowing them lets you adapt to an existing project rather than imposing your own convention.

  • OOCSS (object-oriented CSS) — separates structure from appearance so the same classes can be reused across several components.
  • SMACSS — sorts rules into categories: base, layout, modules, state and theme.
  • Utility classes — small single-purpose classes (.text-center, .mt-4) combined directly in the HTML, an approach popularized by Tailwind.

Structuring your CSS files

On a medium-sized project, it’s common to split the CSS into several files rather than having a single file of several thousand lines.

file-structure.txt
styles/
├── base.css         (reset, variables, base html/body styles)
├── typography.css   (headings, paragraphs, links)
├── buttons.css      (styles for "button" components)
├── cards.css        (styles for "card" components)
├── navigation.css   (header, menu)
└── main.css         (imports all the other files)
main.css
@import url("base.css");
@import url("typography.css");
@import url("buttons.css");
@import url("cards.css");
@import url("navigation.css");

A caveat

@import adds an extra network request per file and can slow down loading. On a real project, you’d rather use a build tool (Vite, which powers Astro) to automatically merge the CSS files into a single optimized file at build time.

In what order should you write your CSS?

Order matters, because with equal specificity, the last rule wins. A common organization goes from the most general to the most specific: first what applies to the whole page, then components, finally special cases. This way, precise rules naturally override general ones without conflict.

global-order.txt
1. Reset and variables      (base values, whole site)
2. Base styles             (body, headings, links, paragraphs)
3. Layout                  (grids, containers, header, footer)
4. Components              (buttons, cards, forms)
5. Utilities and exceptions (adjustment classes, special states)

Ordering declarations within a block

Within a rule, always adopting the same order makes the code more readable. A common convention groups properties by family: positioning, box, typography, then decoration. It doesn’t matter which order you choose; what matters is staying consistent with it.

declaration-order.css
.card {
  /* 1. Positioning */
  position: relative;
  top: 0;

  /* 2. Box */
  display: block;
  width: 100%;
  padding: 20px;
  margin-bottom: 16px;

  /* 3. Typography */
  font-size: 1rem;
  color: #1e293b;

  /* 4. Decoration */
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

A minimal CSS reset

Browsers apply default styles that differ slightly from one another (margins, font sizes...). A small “reset” at the start of the file harmonizes this starting point.

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

body {
  line-height: 1.5;
  -webkit-font-smoothing: antialiased;
}

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

button, input, textarea, select {
  font: inherit; /* inherits the parent's font instead of the browser's native style */
}

Commenting and sectioning a file

In a long file, section comments serve as visual landmarks: you spot them at a glance while scrolling, and they let you quickly find a component. A comment should explain thewhy of a choice, not repeat what the code does.

comments.css
/* ==========================================================
   CARDS
   ========================================================== */

.card { padding: 20px; }

/* Minimum height needed to avoid a layout shift
   when the image loads after the text. */
.card__image { min-height: 180px; }

Importing your files in an Astro project

In Astro, rather than using @import, you import the CSS file directly from a component or a layout. The build takes care of merging and optimizing the styles. You can thus keep a split into several files for working comfort, without hurting loading performance.

Layout.astro (frontmatter excerpt)
import "../styles/base.css";
import "../styles/cards.css";
import "../styles/navigation.css";

Naming states with dedicated classes

For states managed by JavaScript (open menu, active button, field with an error), an explicit prefix like is- or has- is often used. The prefix immediately signals that this is a temporary state, added and removed dynamically, and not a permanent variant like a BEM modifier.

state-classes.css
.menu { display: none; }
.menu.is-open { display: block; }        /* state: the menu is open */

.field.has-error { border-color: #b91c1c; } /* state: the field contains an error */

Utility classes in practice

A utility class does one single thing, and always does it the same way. It’s ideal for small recurring adjustments (alignment, margin, hiding) that would be tedious to recreate in every component. Used in moderation and placed at the end of the stylesheet, it complements BEM without replacing it.

utilities.css
.text-center { text-align: center; }
.mt-4        { margin-top: 1rem; }
.hidden      { display: none; }

/* They go last so they can override components */

Clean up regularly

Growing CSS accumulates dead code: rules that no element uses anymore. Get into the habit of deleting classes that have become useless and merging duplicate rules. A shorter file is a file that loads faster and is easier to understand.

Classic pitfalls to avoid

  • Too many !important — almost always a sign of poorly mastered specificity rather than a real necessity.
  • Over-nested selectors — .page .content .article .title span is fragile and hard to override; prefer a single, descriptive class.
  • Repeated magic values — writing #6d28d9 in 15 places instead of using a CSS variable: the day you need to change the color, it’s 15 edits instead of one.
  • Forgetting box-sizing: border-box; — a classic source of unexpected layout overflows.

A checklist before shipping

Before considering a project clean, a few quick questions help spot the most common weaknesses of a stylesheet.

  • Does each class have a name that describes its role rather than its appearance?
  • Are repeated colors, spacing and radii grouped into variables in :root?
  • Are the files split by topic (base, components, navigation) and loaded in the right order?
  • Are there any !important declarations or selectors more than three levels deep that could be simplified?
  • Could a colleague find and modify a component in under a minute?

And after pure CSS?

On real projects, many teams use CSS frameworks to move faster and stay consistent, without reinventing these conventions every time: that’s the whole point of the next course.

Exercise

Take one of your existing cards and rename its classes following the BEM convention (card,card__title,card__text).

Exercise: refactor a selector

Find an over-nested selector in your CSS (three levels or more) and replace it with a single BEM class. Check that the appearance is identical, then compare the specificity before and after.

Exercise: organize a file

Take a messy CSS file and reorganize it: reset and variables at the top, then base styles, layout, components and utilities, adding a section comment for each part.

Going further

Add a small CSS reset (like the one above) at the very top of your main file, then replace all your hard-coded colors with CSS variables grouped in:root.