All articles
Formatters
23 min readBy Akash Bijwe

CSS Formatting and Maintainable Stylesheet Architecture

Learn CSS formatting conventions, BEM and other naming methods, cascade layers and Stylelint so your stylesheets stay readable as projects grow.

CSS Formatting and Maintainable Stylesheet Architecture

CSS is easy to start and hard to keep tidy. A stylesheet that was clean in week one can become a thousand-line tangle by month six, where nobody dares delete a rule and every change breaks something elsewhere. This guide covers two linked topics: how to format CSS so it stays readable, and how to organise it so it stays maintainable as a project grows. You will learn the formatting conventions worth following, the naming and architecture methods teams rely on, and how to automate the boring parts.

What is CSS formatting, and why does it matter?

CSS, short for Cascading Style Sheets, describes how HTML elements look. The browser ignores most whitespace in a stylesheet, so these two rules are identical to it:

.card{padding:16px;border:1px solid #ddd;border-radius:8px;background:#fff}
.card {
  padding: 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: #fff;
}

For people the second version is far better. Consistent formatting helps in four ways:

  • Scanning. One declaration per line lets you find a property instantly.
  • Cleaner diffs. When each declaration sits on its own line, a version-control diff shows exactly which property changed.
  • Fewer merge conflicts. Two developers editing different properties of one rule will not collide if they are on separate lines.
  • Fewer mistakes. A missing semicolon or brace is easy to spot in a regular layout and almost invisible in a minified blob.

Formatting is about layout only. Architecture, covered later, is about how rules are named, grouped and layered. You need both.

Core formatting conventions

Teams differ on details, but most agree on the same foundations. The MDN CSS reference shows this layout in almost every example.

One declaration per line. Put each property: value; on its own line, indented one level inside the braces.

A space after the colon, none before. Write color: red;, not color:red; or color : red;.

Always end with a semicolon. Even the last declaration. Adding a property later will not break anything.

Opening brace on the selector line. Write .card {, and close with } on its own line.

One selector per line in a list. When grouping selectors, break them up:

h1,
h2,
h3 {
  margin-block: 0 0.5em;
}

Blank line between rules. It separates ideas visually.

Lowercase everything you control. Properties, keywords and hex colours are case-insensitive, but lowercase is the norm.

Prefer shorthand carefully. margin: 0 auto; is compact, but shorthand resets every sub-property, so use longhand when you only mean to change one value.

Ordering declarations

There is no single correct order, but a predictable one helps. Common approaches are:

  1. Alphabetical. Easy to follow and easy to automate, but it separates related properties.
  2. Grouped by type. Layout first (display, position, flex or grid), then box model (width, margin, padding), then typography, then visual effects (colour, background, shadow). This reads like a story.
  3. No enforced order. Simplest, but least consistent.

Pick one and enforce it with a tool. The order matters less than the agreement.

Why unmaintainable CSS happens

Understanding the failure modes explains the architecture methods that follow. The language has three features that cause problems at scale:

Global scope. Every rule can affect every matching element on the page. Add .title { color: red; } in one file and you may restyle a heading in a completely unrelated component.

The cascade and specificity. When several rules match, the browser picks a winner using origin, specificity and order. As a result, developers fight conflicts with ever more specific selectors, and eventually reach for !important. The article on specificity on MDN explains the scoring system precisely.

Append-only habits. It is safer to add a new override than to edit an old rule, because you do not know what depends on it. Over time the stylesheet only grows.

A good architecture limits global reach, keeps specificity low and flat, and makes it obvious where a style lives.

Naming and organisation methods

BEM

BEM (Block, Element, Modifier) is a naming convention that makes a class name tell you its role. The official BEM introduction defines it as follows:

  • Block: a standalone component, such as card.
  • Element: a part of a block, written card__title.
  • Modifier: a variation, written card--featured.
.card { padding: 16px; }
.card__title { font-size: 1.25rem; }
.card--featured { border-color: gold; }

Because every selector is a single class, specificity stays flat and rules are easy to override predictably. The downside is long class names.

Other approaches

  • OOCSS (Object-Oriented CSS) separates structure from skin and encourages reusable "objects".
  • SMACSS sorts rules into categories: base, layout, module, state and theme.
  • ITCSS (Inverted Triangle CSS) orders files from low-specificity, far-reaching rules to high-specificity, narrow ones: settings, tools, generic, elements, objects, components, utilities.
  • Utility-first CSS builds interfaces from small single-purpose classes. It trades long HTML for very little custom CSS.
  • CSS Modules and CSS-in-JS generate locally scoped class names at build time, which solves global scope by tooling rather than convention.

None of these is universally best. BEM or a similar naming convention suits server-rendered sites, while component frameworks often pair with CSS Modules or utilities.

Modern CSS features that help architecture

The language itself has improved, and several features reduce the need for workarounds.

Custom properties. CSS variables let you define design tokens once and reuse them everywhere:

:root {
  --color-brand: #2563eb;
  --space-2: 0.5rem;
  --radius: 8px;
}

.button {
  background: var(--color-brand);
  padding: var(--space-2) calc(var(--space-2) * 2);
  border-radius: var(--radius);
}

Cascade layers. The @layer rule lets you declare the order of whole groups of styles, so the order wins over specificity. You can put resets, base styles, components and utilities in named layers and know which beats which. See the @layer reference on MDN.

Native nesting. Browsers now support nesting rules, which keeps related styles together without a preprocessor.

:where() and :is(). :where() has zero specificity, which is ideal for resets and defaults that should be easy to override.

Real-world use cases

Cleaning up a minified file. You inherit a production stylesheet or copy a rule from browser developer tools, and it is on one line. Formatting it is step one to reading it.

Taking over a legacy project. Before refactoring, normalise the formatting in a single commit so later diffs show only meaningful edits.

Standardising a team. Agree a style once, run it automatically, and remove style comments from code review.

Documenting and teaching. Well-formatted CSS examples are easier to read in tutorials, slides and bug reports.

Common mistakes

  • Over-nesting selectors. .page .sidebar .list .item a is brittle and hard to override. Keep selectors shallow.
  • Using IDs for styling. IDs carry high specificity and cannot be reused. Prefer classes.
  • Reaching for !important. It is a sign of a specificity problem. Fix the cause, or use cascade layers.
  • Styling by tag name inside components. .card div breaks when markup changes. Give elements their own classes.
  • Copy-pasting rules. Duplication means a change must be made in many places. Extract shared values into custom properties.
  • Never deleting anything. Dead CSS bloats the file. Remove unused rules periodically.

Step-by-step: format CSS with DevUtilX

For a quick clean-up with no setup, the DevUtilX CSS Formatter works in the browser.

  1. Open the CSS formatter tool.
  2. Paste your minified or messy CSS into the input editor.
  3. Choose your indentation (spaces or tabs).
  4. Run the formatter and read the tidy output.
  5. Copy the result back into your project.

Processing happens in your browser, so your styles are not uploaded. After formatting, run the code through the CSS Validator to catch syntax errors, and when you are ready to ship use the CSS Minifier to shrink it again.

Automating formatting and linting in a project

Manual formatting does not scale, so automate it.

Format with Prettier. Prettier formats CSS, SCSS and Less with sensible defaults, and the setup is a few lines of config. Our guide to JavaScript code formatting covers the same tooling in more depth.

Lint with Stylelint. Stylelint finds errors and enforces conventions. It can flag invalid values, duplicate selectors, overly high specificity and unknown properties. A small config:

{
  "extends": ["stylelint-config-standard"],
  "rules": {
    "selector-max-id": 0,
    "declaration-no-important": true
  }
}

Share editor settings. An .editorconfig file keeps indentation consistent across editors.

Enforce in CI. Run the format check and linter on every pull request so unformatted or rule-breaking CSS cannot merge.

Keep a clear split of duties, the same one used with JavaScript: let the formatter own layout and let the linter own correctness and conventions. Disable any Stylelint rule that only concerns formatting.

Best practices

  • Pick conventions once and automate them. Consistency beats personal preference.
  • Keep specificity low and flat. Prefer single-class selectors.
  • Use custom properties for design tokens. Colours, spacing and radii belong in variables.
  • Organise by component. Keep a component's styles together and name them predictably.
  • Layer your styles. Use @layer or an ITCSS-style file order so precedence is intentional.
  • Comment sparingly but usefully. Explain why a hack exists, not what a property does.
  • Remove dead code. Audit unused CSS from time to time.
  • Minify for production only. Keep source files formatted and let the build minify them.

Comparison and alternatives

Approach Strength Trade-off
Plain CSS with BEM No tooling, flat specificity Long class names, discipline needed
Sass or SCSS Variables, mixins, nesting Build step; much now possible in native CSS
CSS Modules Local scope by default Requires a bundler
Utility-first CSS Fast to build, small output Verbose markup
CSS-in-JS Co-located, dynamic styles Runtime or build cost

Whichever you choose, the formatting rules in this guide apply. If you work with preprocessors, you may also like to read about validating Sass and SCSS in our upcoming guides.

How the browser decides which rule wins

Most architecture advice is a defence against one question: when two rules disagree, which one applies? Knowing the exact answer lets you design stylesheets that rarely need to ask.

The browser sorts competing declarations using these criteria, in this order:

  1. Origin and importance. Browser defaults, author styles and user styles sit in different origins, and !important flips their priority.
  2. Cascade layers. Within the author origin, a rule in a later layer beats a rule in an earlier layer, regardless of specificity. Unlayered styles beat all layered styles for normal declarations.
  3. Specificity. Counted as three numbers: IDs, then classes, attributes and pseudo-classes, then type selectors and pseudo-elements.
  4. Source order. If everything else ties, the last declaration wins.

Specificity is compared column by column, not added up as one number. Here is a worked example:

.nav a            /* (0,1,1) */
.nav a:hover      /* (0,2,1) */
#menu             /* (1,0,0) */
:where(.nav) a    /* (0,0,1): :where() adds nothing */

Each comment shows the score for the selector beside it. .nav a scores (0,1,1): one class and one type selector. Adding :hover raises it to (0,2,1). A single ID, (1,0,0), beats any number of classes, because the columns are compared left to right. That is why IDs and long chains of classes are such a bad habit: they force every later override to climb higher.

The practical lesson is that you control two of these four levers on purpose. Keep specificity flat so the third lever rarely matters, and use layers so the second lever is explicit. Source order then becomes a simple, predictable tie-breaker rather than a source of surprises.

What a formatter actually does to your CSS

A CSS formatter does not understand your design. It reads the stylesheet as a stream of tokens (selectors, braces, property names, values, comments and strings), then writes the same tokens back with consistent whitespace. Knowing this explains both its power and its limits.

A good formatter does the following:

  • Puts each declaration on its own line and indents it.
  • Adds a space after each colon and a space before each opening brace.
  • Splits comma-separated selector lists onto separate lines.
  • Inserts blank lines between rules.
  • Indents nested rules and at-rule bodies, such as everything inside @media.

It must also leave some things alone. Whitespace inside a string, a url() and a quoted font name is meaningful. Comments must survive in place. Custom property values can hold almost any token sequence, so a formatter should treat them with care. Here is a before-and-after on a tricky input:

@media (min-width:48rem){.hero{background:url("img/a b.png") no-repeat;--shadow:0 1px 2px rgb(0 0 0/.2),0 4px 8px rgb(0 0 0/.1)}.hero>h1{margin:0}}
@media (min-width: 48rem) {
  .hero {
    background: url("img/a b.png") no-repeat;
    --shadow:
      0 1px 2px rgb(0 0 0/0.2),
      0 4px 8px rgb(0 0 0/0.1);
  }

  .hero > h1 {
    margin: 0;
  }
}

Details vary between tools. Some add the leading zero in .2, some break long comma lists across lines, and some leave custom properties exactly as written. That is why you should pick one formatter for the whole team: two tools with different opinions will fight over every file.

A formatter does not fix invalid CSS. If a brace is missing, the output may be wrong or the tool may refuse to run. Run the CSS Validator when a formatted file looks strange, because the problem is probably in the input.

Worked example: untangling a real-looking stylesheet

Abstract rules are easier to remember when you see them applied. Consider this fragment, typical of a stylesheet that has grown by accretion:

#sidebar .widget ul li a { color: #333; text-decoration: none; }
.widget a { color: #0645ad !important; }
div.widget ul li a:hover { color: red; }
.sidebar-widget-title, .widget h3 { font-size: 18px; margin: 0 0 8px 0; font-weight: bold; }

It has four problems. The ID selector forces everything else to compete. The !important was probably added to beat the first rule. The hover rule uses a type selector for no reason. The heading is styled in two overlapping ways.

Refactor in four steps.

Step 1: format first. Run the formatter and commit only that change. Every later diff then shows real edits.

Step 2: give the component a block name. Decide that this is a widget, with a title and a link. Add classes to the markup: widget, widget__title, widget__link.

Step 3: move values into tokens. The repeated colours and sizes become custom properties.

Step 4: write flat selectors.

:root {
  --color-link: #0645ad;
  --color-link-hover: #b00020;
  --text-lg: 1.125rem;
  --space-1: 0.5rem;
}

.widget__link {
  color: var(--color-link);
  text-decoration: none;
}

.widget__link:hover {
  color: var(--color-link-hover);
}

.widget__title {
  margin: 0 0 var(--space-1);
  font-size: var(--text-lg);
  font-weight: 700;
}

Every selector now has the same specificity of one class (plus a pseudo-class for hover). The !important is gone because nothing needs to win by force. The rules are shorter, and a developer who sees widget__link in the markup knows exactly where to look in the CSS.

Do this one component at a time. A big-bang rewrite of a whole stylesheet is risky; a steady migration is not.

Cascade layers in practice

Cascade layers are the most useful structural feature added to CSS in recent years. A layer is a named bucket of rules whose priority is decided by declaration order, not by specificity.

Declare the order once, at the top of your entry stylesheet:

@layer reset, tokens, base, components, utilities;

Then place styles into those layers:

@layer reset {
  *,
  *::before,
  *::after {
    box-sizing: border-box;
  }
}

@layer components {
  .button {
    padding: 0.5rem 1rem;
    background: var(--color-brand);
  }
}

@layer utilities {
  .hidden {
    display: none;
  }
}

A .hidden rule in utilities now beats .button in components even if the component selector were body .page .button, because utilities comes later in the declared order. You no longer need !important for utilities.

A few behaviours surprise people the first time:

  • Unlayered CSS wins. For normal declarations, styles outside any layer beat all layered styles. If you add layers to an existing project, old unlayered rules will still override your layers. Move them in gradually.
  • !important reverses the order. An important declaration in an earlier layer beats an important declaration in a later one. This lets a reset layer protect critical rules, but it is easy to forget.
  • Import into a layer. You can load a third-party stylesheet into a low-priority layer with @import url("vendor.css") layer(vendor);. Your own unlayered styles then override the library without any specificity tricks.
  • Order is fixed by first mention. The first time the browser sees a layer name, it fixes that layer's position. A single declaration line at the top prevents accidents.

Layers are supported in current versions of all major browsers. If you must support much older browsers, check a compatibility table such as the one on the @layer MDN page before depending on them.

Native nesting: convenience and traps

Nesting lets you write child rules inside a parent, which keeps a component's styles in one visible block:

.card {
  padding: 1rem;

  & .title {
    font-size: 1.25rem;
  }

  &:hover {
    box-shadow: 0 2px 8px rgb(0 0 0 / 0.15);
  }

  &.is-featured {
    border-color: gold;
  }

  @media (min-width: 48rem) {
    padding: 2rem;
  }
}

The & stands for the parent selector. It is needed when you attach something directly to the parent, as in &:hover and &.is-featured. Without the ampersand, :hover alone would mean "any hovered descendant", which is almost never what you want.

Three habits keep nested CSS healthy:

  • Limit depth to two or three levels. Deep nesting recreates the long selectors that BEM was invented to avoid.
  • Remember the specificity. A nested & .title behaves like .card .title, which scores (0,2,0), not (0,1,0). Nesting does not make selectors flatter.
  • Do not build class names with &. Some preprocessors let you write &__title to produce .card__title. Native CSS does not support that. A search for .card__title will find a native stylesheet; it will not find a preprocessor trick.

A formatter should indent nested rules by one level and keep a blank line before them. Check that your tool supports nesting before you adopt it widely, since older formatter versions may reject the syntax.

Setting up the toolchain step by step

Here is a complete, minimal setup for a project that uses npm. It takes about ten minutes.

1. Install the tools.

npm install --save-dev prettier stylelint stylelint-config-standard

Recent Stylelint versions have deprecated their own formatting rules, so you usually do not need a config that switches them off. Check the Stylelint documentation for the version you install.

2. Configure Prettier in .prettierrc:

{
  "tabWidth": 2,
  "singleQuote": false
}

3. Configure Stylelint in .stylelintrc.json, as shown earlier in this guide, and add any project-specific rules.

4. Add scripts to package.json:

{
  "scripts": {
    "format": "prettier --write \"src/**/*.css\"",
    "format:check": "prettier --check \"src/**/*.css\"",
    "lint:css": "stylelint \"src/**/*.css\""
  }
}

5. Share editor settings with an .editorconfig:

root = true

[*.css]
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

6. Format on save. Most editors can run Prettier when you save a file. Turn this on in the workspace settings and commit the settings file so every teammate gets the same behaviour.

7. Check staged files before each commit. A tool such as lint-staged runs the formatter and linter on only the files you changed, which keeps the hook fast:

{
  "lint-staged": {
    "*.css": ["prettier --write", "stylelint --fix"]
  }
}

8. Fail the build in CI. Run npm run format:check and npm run lint:css in your pipeline. A pull request with unformatted CSS then fails with a clear message, and the author fixes it before review.

Order matters in step 7. Run the formatter first, then the linter with --fix, so the linter sees final whitespace.

Keeping declaration order consistent

If your team wants grouped or alphabetical properties, Prettier will not do it, because it never reorders declarations. Add the stylelint-order plugin and enable its rules, for example order/properties-alphabetical-order, or define your own groups. Autofix can then reorder properties on commit. Reordering is safe in almost every case, with one exception: when a shorthand and a longhand for the same property appear together, their order changes the result. A good ordering rule keeps shorthands before their longhands.

Troubleshooting: symptom, cause, fix

Symptom Likely cause Fix
A rule has no effect A more specific or later rule overrides it Inspect the element in developer tools and look for a struck-through declaration; fix order or layers, not specificity
Style works on one page, breaks on another Global selector leaking between components Scope the rule to a block class or move it into a layer
!important needed to win Specificity war, often with an ID or third-party CSS Flatten selectors; load vendor CSS into a low layer
Layered rule loses to an old rule Old rule is unlayered and unlayered beats layered Move the old rule into a layer, or wrap legacy CSS in one
Formatter fails or output looks broken Invalid syntax such as a missing brace Validate the input first and fix the first reported error
Formatter and linter disagree Both enforce layout rules Let the formatter own layout and turn off formatting rules in the linter
Huge diff after formatting File was never formatted before Commit the formatting alone, then record the commit in your blame-ignore list
Variable shows as unset Custom property declared on a child, or a typo in its name Declare tokens on :root; check the name for typos
Rules after a certain point are ignored An unclosed brace earlier swallowed them Run the validator and read the first error, not the last
Nested rule matches too much Missing & before a pseudo-class Write &:hover instead of :hover

Two debugging habits save the most time. First, always check computed styles in the browser's developer tools, which show which declaration won and which were overridden. Second, bisect: delete half of the suspect CSS, see whether the bug survives, and repeat. A well-formatted file makes this easy because each rule is a visible, self-contained block.

If you suspect a recent change broke something, compare the old and new files with the techniques in our guide to code diffing and comparing files.

Performance considerations

CSS performance is mostly about delivery, not about how fast a selector matches. Still, a few architectural choices matter.

Delivery size and blocking. The browser will not paint a page until it has downloaded and parsed the stylesheets referenced in the head, because CSS blocks rendering. Smaller files arrive sooner. Keep formatted source in your repository and ship minified output; our guide to CSS minification and critical CSS covers inlining the rules needed for the first paint.

Selector matching. Browsers evaluate selectors from right to left. For .nav ul li a, the engine finds every a first and then checks its ancestors. Modern engines are fast, so you will rarely see a problem from this. Short selectors with a single class are cheap, and they are also better for maintenance. Treat performance as a bonus of flat selectors rather than a reason to rewrite working code.

Dead CSS. Unused rules cost bytes to download and time to parse. Over a long project they accumulate. Use the coverage tool in browser developer tools to see which rules a page never used, and treat the result with caution: a rule unused on one page may be needed on another or only after interaction. Audit across your key pages and states before deleting.

Expensive properties. Large blurred shadows, filters and backdrop effects cost more to paint than plain colours. If a stylesheet applies them to many elements, check scrolling and animation smoothness on a mid-range phone. Animate transform and opacity where you can, since they usually avoid layout work.

Many small files. Splitting CSS into dozens of files helps authors but can hurt users if each file is a separate request. Bundle at build time and let your bundler produce a small number of output files.

Accessibility rules that belong in your CSS standards

Architecture decisions affect real users, and a few rules are worth writing into your team conventions.

  • Never remove focus outlines without a replacement. outline: none on a link or button makes keyboard navigation impossible to follow. Style :focus-visible instead, which shows a ring for keyboard users without distracting mouse users.
  • Respect motion preferences. Wrap large animations in a prefers-reduced-motion query, or disable them inside it.
  • Check contrast in the token file. Define colour pairs as tokens and verify text and background combinations once, rather than auditing each component.
  • Use relative units for text. Sizes in rem follow the user's browser font setting; fixed pixel sizes may not.
  • Do not hide content with display: none if screen readers need it. Use a visually hidden utility class for text that is only for assistive technology.
  • Support forced colours. Windows high-contrast mode overrides your palette. Avoid relying on background colour alone to show state, and test with the forced-colors media feature when you build custom controls.

A common reduced-motion pattern looks like this:

@media (prefers-reduced-motion: reduce) {
  *,
  *::before,
  *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
  }
}

This is one of the few places where !important is a sensible choice, because the user's preference must win over every component.

Our guide to HTML formatting and semantic markup explains why good markup comes first: CSS cannot rescue a button that is really a div.

Security considerations

CSS looks harmless, but it is not inert, and a few rules apply to any site that mixes user input with styles.

Never insert untrusted input into a stylesheet. If an application builds CSS by concatenating user-supplied values, an attacker may be able to inject extra rules. Injected CSS can hide or reposition page elements to mislead users, and with attribute selectors that request background images it can leak small pieces of page data to another server. Validate values against a strict allow-list, such as a fixed set of colour names or a pattern for hex colours, before they reach a style.

Prefer setting custom properties. If users may choose a theme colour, set a single custom property from validated input instead of building a whole rule from a string.

Use a Content Security Policy. A style-src directive limits where styles may come from and whether inline styles are allowed. Strict policies break inline style attributes, which is another reason to keep styling in classes.

Audit third-party CSS. A remote stylesheet can change at any time, and loading it also sends a request to the other host. Self-host the files you depend on where you can, and pin versions.

Watch url() values. Every url() triggers a request when the rule applies. Confirm that fonts and images come from hosts you trust.

Migrating a legacy codebase in stages

You rarely get to start from scratch. This path moves an old stylesheet toward a maintainable one with low risk.

  1. Take a baseline. Record screenshots of your main pages and states so you can see regressions. Even manual checks of a short list of pages are better than none.
  2. Format everything in one commit. Add the formatter and linter configs in the same change, and keep that commit free of logic changes.
  3. Turn on the linter in warning mode. Fix errors first, then raise strictness gradually. Start with rules that catch real bugs, such as duplicate selectors and invalid values.
  4. Wrap legacy CSS in a layer. Put the whole old file in a low-priority layer such as legacy. New code in later layers can then override it without specificity battles.
  5. Introduce tokens. Replace repeated colours, spacing and font sizes with custom properties as you touch each area.
  6. Rewrite by component. When you change a component for any reason, rewrite its styles with flat, named selectors, and delete the old rules in the same pull request.
  7. Measure dead code. After a few releases, use coverage data across your main flows to prune what is left.
  8. Lock the rules in. Once the legacy layer is small, forbid new additions to it in code review or by a lint rule.

The key idea is that every change leaves the code slightly better than you found it. There is no deadline for a perfect result, and no need to stop feature work.

Team conventions checklist

Write your decisions down in a short document in the repository and link to it from your contribution guide. A useful checklist covers:

  • Formatter and version. Name the tool and pin its version so output does not drift.
  • Indentation and line endings. Mirror them in .editorconfig.
  • Naming method. BEM, utility classes or CSS Modules, and what to do when a component is not obviously a block.
  • File layout. Where tokens, base styles, components and utilities live, and the layer order.
  • Selector rules. No IDs, no qualifying a class with a tag, a maximum depth, and when !important is allowed.
  • Token usage. Which values must be tokens, and who may add new ones.
  • Property order. Grouped or alphabetical, enforced by lint.
  • Responsive approach. Mobile-first min-width queries, shared breakpoint values and where they are defined.
  • Review rules. Formatting is never a review comment; the tools handle it.
  • Browser support. The browsers you support and how you decide when to adopt a new feature.

Short documents get read. One page that the whole team follows beats a long manual that nobody opens.

Case study: a design-token rollout

Consider a team with a marketing site and a web app that share a brand. Both repeat the brand blue as a hex value in many places, and a rebrand means a risky find-and-replace across both codebases.

The team starts by formatting both repositories, so searches return consistently laid-out lines. They then extract colours, spacing and type sizes into one shared tokens file of custom properties. Components switch from literal values to var(--color-brand) and similar names as they are edited.

When the rebrand arrives, the change is one file. Because the tokens are custom properties, a dark theme also becomes a small block that redefines them on a parent selector or inside a prefers-color-scheme query, with no changes to component rules. The lasting benefit was not speed on the day but confidence: reviewers could see in a short diff exactly what changed.

FAQ

Should I use tabs or spaces in CSS?
Either is fine. Two spaces is the most common choice. Choose one, put it in your config, and let the tool enforce it.

Does formatting change how my CSS works?
No. A formatter only changes whitespace. Selectors, properties and values are untouched, so rendering stays identical.

Is BEM still relevant?
Yes, especially for projects without a component framework. Its core idea, flat single-class selectors with clear names, is useful in any methodology.

Should I alphabetise my properties?
It is a reasonable default because it needs no thinking and is easy to automate. Grouping by type reads better to some teams. Both are acceptable if applied consistently.

When is !important acceptable?
Rarely: for utility classes that must always win, or to override third-party styles you cannot edit. Cascade layers are usually a better tool.

Should I format or minify before deploying?
Both, in order. Keep formatted source in your repository and minify the output during your build.

Why does my new rule lose even though it comes later in the file?
A rule that comes later only wins when origin, layer and specificity all tie. Check for a more specific selector, an !important elsewhere, or an unlayered rule beating your layered one. The computed styles panel in browser developer tools shows the winner.

Do cascade layers replace BEM?
No. Layers decide which group of styles wins, while BEM names things inside a group. They work well together: BEM keeps selectors flat, and layers make precedence between groups explicit.

Can I use native nesting without a build step?
Yes, in current browsers. Check your support targets first, and confirm your formatter and linter versions understand the syntax, or they may report false errors.

How do I stop a huge formatting commit from ruining git blame?
Commit the formatting change by itself and list its hash in a file passed to git blame --ignore-revs-file. Many hosting sites read the same list from a file named .git-blame-ignore-revs.

Should custom properties hold every value?
No. Tokens are for values that carry design meaning and repeat, such as colours, spacing and radii. A one-off value used in a single rule is clearer when written inline.

Is it safe to let users customise colours?
Yes, if you validate the input against a strict pattern and set it through a custom property. Never build whole rules from user-supplied strings.

Conclusion

Readable CSS comes from two habits: a consistent format and a deliberate structure. Format with one declaration per line, automate it with Prettier and Stylelint, name things with a method such as BEM, keep specificity flat, and use custom properties and cascade layers to make precedence explicit. For a fast clean-up of any stylesheet, try the CSS Formatter, and read our JSON Formatting Guide for the same principles applied to data.

Further reading

Try the tools

Further reading

Related articles