Chuyển đến nội dung

Bài 35 · Migration and Best Practices

Sass Best Practices, Pitfalls and Sass vs Modern CSS

A practical Sass style guide: naming, nesting limits, variables vs custom properties, documentation with SassDoc, common pitfalls, and an honest comparison of Sass with modern native CSS.

Sass gives you a lot of power, and power without habits produces tangled code. This lesson collects the practices that experienced teams settle on, the pitfalls that beginners fall into, and a candid answer to a question you will hear: "CSS has nesting and variables now, so do I still need Sass?"

Part 1: Style guide

Structure and naming

  • One purpose per file. _button.scss contains the button and nothing else. Name partials after their content.
  • Use @use, never @import, at the top of the file. Put sass: modules first, then your own modules, then third-party.
  • Short namespaces with as for deep paths: @use "../abstracts/tokens" as t;.
  • Lowercase with hyphens for variables, mixins, functions and class names: $font-stack, @mixin focus-ring, .main-nav. Use BEM for component classes (details).
  • Private by default. Prefix helpers with - and expose only what consumers need.
  • Prefix nothing that a namespace already names. tokens.$color-primary is clearer than tokens.$tokens-color-primary.

Variables and tokens

  • Sass variables for build-time values (breakpoints, which cannot be CSS variables inside media queries, and values used in Sass math).
  • CSS custom properties for run-time values (themes, user preferences, values JavaScript changes). See design tokens.
  • Use semantic names: $color-danger, not $red; $space-card, not $space-20px.
  • Mark library settings !default and document them.
  • Avoid global state. A mixin that reads a variable another file mutated is a bug generator; pass arguments instead.

Nesting and selectors

  • Nest at most three levels, not counting & pseudo-classes and modifiers.
  • Do not nest to mirror the HTML. Give elements classes.
  • Avoid element selectors inside components (div, span); they break the moment markup changes.
  • Avoid #id selectors and !important. If you must override third-party CSS, do it in a clearly named themes or overrides file.
  • Use & deliberately: &:hover, &--modifier, .context &. Avoid clever string building (&-#{$x}-#{$y}), which makes names impossible to search.

Mixins, functions and extend

  • Functions return values; mixins output CSS. Do not make a mixin when a function would do.
  • Validate arguments with @error and a message listing the valid choices.
  • Give arguments defaults where a sensible one exists, and use named arguments at call sites for clarity: @include button($size: lg).
  • Prefer mixins to @extend, except for constant style bundles (performance).
  • Keep mixins small. A mixin that emits fifty declarations probably wants to be a component class.

Output discipline

  • No CSS from abstracts. Tokens, mixins and functions emit nothing.
  • Compile with source maps in development, compressed output in production.
  • Check the compiled CSS occasionally. Sass can hide a monster selector behind three lines of nested source.
  • Lint with stylelint and stylelint-config-standard-scss; format with Prettier.

Part 2: Document your code with SassDoc

Triple-slash comments become structured documentation that tools such as SassDoc can publish, and that editors show on hover:

SCSS
/// Converts a pixel value to rem.
/// @param {Number} $px - A length in pixels (unit required).
/// @param {Number} $base [16px] - The root font size.
/// @return {Number} The value in rem.
/// @example scss
///   .title { font-size: to-rem(24px); } // 1.5rem
@function to-rem($px, $base: 16px) {
  @return math.div($px, $base) * 1rem;
}

/// @access private
@mixin -debug-grid { outline: 1px dashed red; }

Document every public function, mixin and configurable variable. A one-line description and the parameters are enough.

Part 3: Common pitfalls

  1. Over-abstracting. A mixin called once is noise. Wait until you see the pattern three times.
  2. Deep nesting from habit. Re-read compiled output; flatten.
  3. A giant _variables.scss holding every value in the project. Split by purpose (colors, spacing, type, components); components own their local variables.
  4. Using @extend across unrelated components, producing selectors like .a, .b, .c, .d, ... where editing one rule changes many things.
  5. Dividing with /. Use math.div.
  6. Hard-coded values next to variables (padding: 13px next to $space-3). Either the scale is wrong or the code is.
  7. Generating names that cannot be searched (.btn-#{$a}-#{$b}). Teams cannot grep them. Document the pattern or write full names.
  8. Treating Sass as the whole system. If a value must change at runtime, it belongs in a CSS custom property.
  9. Dynamic class names in markup. If a utility build is purged, classes assembled at runtime vanish unless safelisted.
  10. Mutating "global" state through !global. Avoid !global; return values instead.
  11. Mixing @import and @use in one project for years. Finish the migration (guide).
  12. Ignoring warnings. Deprecation warnings are an upgrade checklist from the compiler.

Never compile user-supplied Sass on a server without limits. Sass can include files, loop forever and consume memory. If your product lets users enter Sass, run the compiler in a sandbox, restrict loadPaths and importers, and set time limits.

Part 4: Sass versus modern CSS

CSS has absorbed several ideas that once required a preprocessor. Here is the honest comparison:

Feature Native CSS today Sass
Variables Custom properties (--x, var()), live at runtime $x, build time only
Nesting Supported in all modern browsers (& rules) Same idea, plus &-suffix string joining
Color math color-mix(), relative colors, oklch() color.adjust, color.scale, color.mix
Math calc(), min(), max(), clamp(), round(), pow() Full numbers, units, maps, loops
Modules and imports @import (extra request) and @layer for ordering @use, @forward, namespaces, privacy
Loops and conditionals Not available (a conditional if() function is arriving in some browsers) @each, @for, @while, @if
Maps / data structures None Maps and lists
Mixins and functions CSS @function is starting to ship; mixins are proposals Mature @mixin, @function, @content
Inheritance Cascade, @layer, @scope @extend

Check current support on a compatibility table before depending on newer CSS features.

When Sass is still the right tool

  • You generate many rules from data: utility classes, palettes, grids, icon sets.
  • You need build-time computation: modular scales, contrast checks, fluid type formulas, breakpoint maps used in @media.
  • You maintain a design system that needs modules, privacy and library configuration.
  • You have a large legacy Sass codebase that works. Rewriting it is rarely worth it.
  • Your team already thinks in Sass and the tooling is in place.

When plain CSS is enough

  • A small site or component library with a handful of files.
  • Theming through custom properties with native nesting and color-mix().
  • You want zero build step (no compiler, simple deployments).
  • You are following an approach like CSS Modules, @layer and Lightning CSS that already provides what you need.

They work together

The best modern setup uses both: Sass to organize, generate and compute at build time, producing native CSS custom properties and modern features for the browser. The tool below shows a Sass-only feature (data-driven generation with a function) that emits ordinary CSS with custom properties.

Sass computes, CSS themes

Sass computed the strong and soft shades at build time for each palette color; the browser only handles ordinary custom properties. Add purple: #7c3aed to the palette and a fourth theme appears without further code.

Use Sass for build-time work

Generate Loops and maps make many rules
Compute Scales, contrast, fluid math
Organize Modules and privacy

These things happen once, when you build.

1 / 3

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Which is the better home for a theme color that the user can change in the browser?

    Sass variables vanish at build time; custom properties change at runtime.
  2. 2. How deep should Sass nesting normally go?

    Deep nesting inflates selectors, raises specificity and couples styles to markup.
  3. 3. What do triple-slash /// comments provide?

    SassDoc comments describe parameters and return values for documentation tools and editors.
  4. 4. Which is a task where Sass is still clearly better than plain CSS?

    Loops and maps do not exist in CSS, so generation stays a Sass job.
  5. 5. What is a good response to a deprecation warning?

    Warnings tell you what will break in a future major version.

Summary

  • Keep files single-purpose, use @use, lowercase-hyphen names, private helpers, shallow nesting and mixins over @extend.
  • Sass variables for build time; CSS custom properties for runtime; semantic token names.
  • Document public APIs with SassDoc and validate arguments with @error.
  • Avoid over-abstraction, giant variable files, !global, unsearchable generated names and ignored warnings.
  • Native CSS now covers variables, nesting and color mixing; Sass remains best for generation, computation, modules and design systems, and the two combine well.

Next: Project: A Design System Stylesheet

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.