Sub topic 5
Organising files and folders
CSS that grows past a few hundred lines needs a structure. This chapter covers how to split stylesheets into files, how to group those files into folders, and how to decide where a new rule goes. It builds on naming conventions and BEM from the earlier chapters.
Prerequisites
This chapter assumes you:
- know CSS selectors, specificity and the cascade
- can link stylesheets to a page and use
@importor a bundler - have used npm from the command line
- have read the chapters on naming conventions and BEM
Why file structure matters
CSS is global. A rule in any file can affect any element on any page. A file layout cannot change that, but it can make the reach of each rule visible. A developer who opens a file should be able to tell what it affects and what it depends on.
A good structure does three things:
- It makes a rule easy to find. You should know which file holds
.card__titlebefore you search. - It makes the order of files meaningful. Later files can override earlier ones, so the order should follow from the nature of each file.
- It limits the cost of a change. Editing one component file should not require checking the whole codebase.
Two common ways to split files
Most projects use one of two top-level splits, or a mix of both.
| Approach | Groups files by | Strength | Weakness |
|---|---|---|---|
| By type | Kind of rule: base, layout, components, utilities | Matches how the cascade works. Order is easy to reason about. | Files for one feature are spread across several folders. |
| By feature | Page or feature: checkout, profile, search | All styles for one feature live together. Deleting a feature is easy. | Shared rules are easy to duplicate. Order between features is unclear. |
A mixed layout is common. Shared, low-level code is grouped by type. Page-specific code is grouped by feature.
A layout grouped by type
The following layout works for many mid-sized sites. The folder names describe what the rules do, and the order runs from the broadest reach to the narrowest.
styles/
main.css
settings/
tokens.css
base/
reset.css
typography.css
layout/
grid.css
page.css
components/
button.css
card.css
nav.css
pages/
checkout.css
utilities/
spacing.css
visibility.cssEach folder has a purpose:
settings/holds design tokens, which are custom properties such as colours and spacing. It produces no output of its own.base/styles bare HTML elements: a reset, body text, headings, links. It uses element selectors only, so specificity stays very low.layout/holds the page skeleton: grids, containers, headers and footers.components/holds one file per reusable component, such as a BEM block.pages/holds rules for one page that no other page needs.utilities/holds single-purpose helper classes. These come last so they can override the rest.
The order of the folders follows a pattern. Rules that reach many elements with low specificity come first. Rules that reach few elements with high impact come last. The next chapter on layered architectures names this pattern explicitly.
One component per file
Give each BEM block its own file, named after the block. The file components/card.css holds .card, .card__title and .card--featured, and nothing else.
/* components/card.css */
.card {
padding: 1rem;
border: 1px solid #ddd;
}
.card__title {
font-size: 1.25rem;
}
.card--featured {
border-color: gold;
}This gives you a predictable mapping between the class name and the file. If you see class="card card--featured" in markup, the styles are in card.css. Because the selectors are single classes, they all have the same specificity, and their order inside the file decides ties.
Follow these rules for component files:
- Name the file after the block, not after the page that uses it.
- Put only that block's selectors in the file. If you need to style an element from another block, create a modifier or a new element in the owning block instead.
- Keep the block's own states and modifiers in the same file.
- Do not reach into another component's internals, for example
.nav .card__title. That ties two files together without showing it.
Combining files with an entry point
A single entry file lists the other files in the intended order. The entry file is where order is decided, so keep it short and readable.
/* main.css */
@import "settings/tokens.css";
@import "base/reset.css";
@import "base/typography.css";
@import "layout/grid.css";
@import "layout/page.css";
@import "components/button.css";
@import "components/card.css";
@import "components/nav.css";
@import "pages/checkout.css";
@import "utilities/spacing.css";
@import "utilities/visibility.css";Native @import has a cost. The browser must download the entry file before it learns about the files it imports, and nested imports load one after another. For a production site, a bundler such as Vite, webpack or PostCSS with postcss-import should inline the imports into one file. In development, native @import is fine.
Two details trip people up:
@importrules must come before all other rules in a file, except@charsetand@layerstatements. An@importplaced after a normal rule is ignored.- Order in the entry file is cascade order. If
utilities/spacing.cssis imported beforecomponents/card.css, a.cardrule can override a utility of equal specificity.
Using layers to make order explicit
Order in an entry file is a convention that anyone can break by reordering lines. Cascade layers turn it into a declaration. The @layer statement fixes the order once, and later chapters cover it in full. Here is how it fits the file layout.
/* main.css */
@layer reset, base, components, utilities;
@import "base/reset.css" layer(reset);
@import "base/typography.css" layer(base);
@import "components/card.css" layer(components);
@import "utilities/spacing.css" layer(utilities);With this setup, the layer order is declared in the first line. Moving an @import line later in the file no longer changes which layer wins. Each import is assigned to a named layer, and the layer statement at the top decides priority.
A diagram helps show the flow from source folders to the delivered file.
Co-locating styles with components
Many projects use a component framework such as React, Vue or Svelte. In that case, keeping the stylesheet next to the component is common.
src/
components/
Card/
Card.tsx
Card.module.css
Card.test.tsx
Button/
Button.tsx
Button.module.css
styles/
tokens.css
reset.css
utilities.cssThis is grouping by feature at the component level. Opening a component's folder shows everything about it. Deleting the folder removes its styles, which prevents dead CSS. Global material, such as tokens, the reset and utilities, stays in a shared styles/ folder.
The trade-off is that shared rules have no obvious home. Decide early where cross-component patterns go, or each team will invent its own place.
Deciding where a new rule goes
When you add a rule, ask these questions in order:
- Is it a value reused across the site, such as a colour or a spacing step? Add a token in
settings/. - Does it style a bare HTML element everywhere? Put it in
base/. - Is it part of the page skeleton? Put it in
layout/. - Does it belong to a reusable block? Put it in that block's file in
components/. - Is it needed on exactly one page? Put it in
pages/. - Is it a single-purpose override? Put it in
utilities/.
If a rule fits more than one answer, pick the earliest one that fits. Rules that sit too late in the order tend to be overrides added in a hurry.
Common mistakes
- A
misc.cssorcommon.cssfile. A file with no clear purpose collects rules that nobody wants to place. Name every file for what it holds, and split a file when its name stops being accurate. - Page files that restyle components. A rule such as
.checkout .button { ... }inpages/checkout.csschanges a component from outside. Add a modifier like.button--wideto the component instead. - Deep folder trees. More than three levels of nesting makes imports long and files hard to find. A flat
components/folder with one file per block is easier to search. - Files that depend on load order without saying so. If
card.cssonly works afterbutton.css, record the dependency or remove it. Layers make such dependencies explicit. - Mixing tokens and rules. A file that defines custom properties and also styles elements is hard to reuse. Keep
settings/free of selectors other than:root. - Many tiny files in production. Splitting source files is good. Delivering a hundred separate requests is not. Bundle for delivery.
A practical migration path
Few teams start with a clean layout. To move an existing stylesheet to this structure without breaking it:
- Create the folders and an entry file that imports the old stylesheet unchanged.
- Extract tokens first. Replace repeated values with custom properties.
- Move one component at a time into its own file. Import it in the entry file in the same position the rules held before.
- After each move, compare the rendered pages. If the output changes, the move changed the cascade order.
- Delete the old rules from the original file only after the new file works.
- When the old file is empty, remove it.
Moving in small steps lets you spot an order problem right after it appears, instead of after dozens of moves.
Summary
- Split files by type for shared code and by feature for page-specific or component-specific code.
- Name each file after what it holds. Use one file per BEM block.
- Order files from broad, low-specificity rules to narrow, high-impact rules.
- Use one entry file to set the order, and bundle it for production.
- Declare the order with
@layerwhen you want it enforced instead of only arranged. - Move code in small steps and check the result after each one.
Exercise
A project has components/card.css and pages/checkout.css. The checkout file contains .checkout .card { padding: 0; }, and a developer asks to move it into card.css so "all card rules are together". What is a better change, and why?
Show answer
Add a modifier to the card block, such as .card--flush { padding: 0; }, in components/card.css, and apply card card--flush in the checkout markup. The original rule has higher specificity than .card because it uses two classes. It also changes a component from outside, so a reader of card.css cannot see it. Moving it into card.css would keep the extra specificity. A modifier keeps specificity at one class and keeps every card variation in the file that owns the block.
Exercise
In the following entry file, a developer finds that .p-0 { padding: 0; } does not override .card { padding: 1rem; } even though both have the same specificity. What is wrong, and how do you fix it?
@import "utilities/spacing.css";
@import "components/card.css";
Show answer
The utilities file is imported before the components file. With equal specificity, the later rule wins, so .card overrides .p-0. Fix it by importing components/card.css first and utilities/spacing.css last. To make this permanent, declare @layer components, utilities; at the top and import each file into its layer, so the utilities layer wins regardless of line order.
Exercise
You are adding a rule that sets max-width: 60ch on every paragraph in the site. Which folder from this chapter should hold it, and why?
Show answer
base/, for example in base/typography.css. The rule styles a bare HTML element across the whole site and uses an element selector, which has the lowest specificity. Putting it in base/ places it early in the order, so components and utilities can override it when needed.