Lesson 12
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.
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.
BEM (Block, Element, Modifier) is a very widespread naming convention that makes the role of each class explicit just by reading it.
<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>/* 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; }
card).__ (card__title).-- (card__button--primary).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.
card__title, not card__body__title.class="card__button card__button--primary"..card__title rather than .card h3./* 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;
}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.
.text-center, .mt-4) combined directly in the HTML, an approach popularized by Tailwind.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.
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)@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.
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.
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)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.
.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);
}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.
*, *::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 */
}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.
/* ==========================================================
CARDS
========================================================== */
.card { padding: 20px; }
/* Minimum height needed to avoid a layout shift
when the image loads after the text. */
.card__image { min-height: 180px; }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.
import "../styles/base.css";
import "../styles/cards.css";
import "../styles/navigation.css";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.
.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 */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.
.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.
!important — almost always a sign of poorly mastered specificity rather than a real necessity..page .content .article .title span is fragile and hard to override; prefer a single, descriptive class.#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.box-sizing: border-box; — a classic source of unexpected layout overflows.Before considering a project clean, a few quick questions help spot the most common weaknesses of a stylesheet.
:root?!important declarations or selectors more than three levels deep that could be simplified?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
card,card__title,card__text).Exercise: refactor a selector
Exercise: organize a file
Going further
:root.