Skip to content
Tutorials Center
My learning

Topics

Lesson 122 of 139 ยท Best Practices

Sass in Practice

A practical guide to Sass and SCSS: set up a project, use variables, nesting, mixins, maps and modules with @use, and see the plain CSS that the compiler outputs.

Preprocessors and Frameworks explained what Sass is and how its ideas compare with native CSS. This lesson is the hands-on follow-up: how a real Sass project is set up, how its features fit together, and what CSS comes out the other end. If you work on an existing codebase, there is a good chance it contains .scss files, so reading them fluently is a valuable skill even if you start new projects with plain CSS.

Sass code needs a compiler, which the browser's live editor cannot run. So the Sass samples here are read-only, and each one is paired with its compiled CSS. The live editors then run that compiled CSS, so you can see exactly what the browser receives.

Setting up Sass

The reference implementation is Dart Sass, distributed on npm as sass. A minimal setup looks like this:

Terminal
npm install --save-dev sass

# compile once
npx sass src/main.scss dist/main.css

# recompile on every save, with source maps for DevTools
npx sass --watch src/main.scss dist/main.css

# a smaller file for production
npx sass --style=compressed --no-source-map src/main.scss dist/main.css

Bundlers such as Vite run Sass for you: install sass, import a .scss file, and the build handles the rest. Either way, the flow is the same:

flowchart LR
  A["main.scss<br/>+ partials"] --> B["Sass compiler"]
  B --> C["main.css"]
  B --> D["main.css.map"]
  C --> E["Browser"]
  D --> F["DevTools shows .scss lines"]

The browser only ever sees the compiled CSS. The source map lets DevTools point back to your original lines.

Variables, with defaults

Sass variables begin with $. Because they exist only at compile time, they suit values that never change at runtime, such as breakpoints. For themeable values, prefer custom properties.

SCSS
$breakpoint-md: 768px;
$font-body: system-ui, sans-serif;
$radius: 8px;

body { font-family: $font-body; }

.card { border-radius: $radius; }

@media (min-width: $breakpoint-md) {
  .card { display: grid; grid-template-columns: 1fr 2fr; }
}

A very useful flag is !default. It means "only set this if nobody has set it already", which lets a consumer configure a library before it loads:

SCSS
// _tokens.scss
$brand: #4f46e5 !default;

Nesting, with the parent selector

Sass nesting is similar to native CSS nesting, and the parent selector & works the same way for states. Sass adds one party trick that native CSS lacks: gluing text onto & to build names.

SCSS
.card {
  padding: 1rem;

  &:hover { box-shadow: 0 6px 18px rgb(0 0 0 / 0.12); }

  &__title { font-size: 1.25rem; }
  &--featured { border: 2px solid gold; }
}

That compiles to .card, .card:hover, .card__title and .card--featured as separate flat rules. It is the main reason BEM projects (see CSS Architecture) often keep Sass. A word of caution: the deeper you nest, the more specific and harder to read the output becomes. Keep nesting to about three levels.

Mixins and functions

A mixin is a reusable block, optionally with parameters. A function returns a value. Both are expanded at compile time.

SCSS
@use "sass:math";

@mixin button-variant($bg, $color: white) {
  background: $bg;
  color: $color;
  border: 2px solid $bg;
}

@function rem($px, $base: 16) {
  @return math.div($px, $base) * 1rem;
}

.btn { padding: rem(8) rem(16); }
.btn-primary { @include button-variant(#4f46e5); }
.btn-danger  { @include button-variant(#dc2626); }

Compiled output:

CSS
.btn { padding: 0.5rem 1rem; }
.btn-primary { background: #4f46e5; color: white; border: 2px solid #4f46e5; }
.btn-danger  { background: #dc2626; color: white; border: 2px solid #dc2626; }

Notice math.div. The old / operator for division is deprecated in Sass, because in CSS the slash can also be a separator (as in font: 16px/1.5). Use math.div(a, b) after loading the built-in module with @use "sass:math".

Run the compiled result below. It is ordinary CSS, and it is all the browser ever sees:

The compiled output of the mixin example

Use mixins for repeated groups of declarations with parameters. If there are no parameters, a shared class or a selector list is often simpler, and a mixin that is included 50 times copies its declarations 50 times into the output.

Maps and loops

A map is a key-value list. Combined with @each it generates families of rules from one data source, a good use of Sass because native CSS has no loops:

SCSS
@use "sass:map";

$colors: (
  "info":    #2563eb,
  "success": #15803d,
  "danger":  #dc2626,
);

@each $name, $value in $colors {
  .badge-#{$name} {
    background: $value;
    color: white;
  }
}

.alert { border-color: map.get($colors, "danger"); }

The #{ } syntax is interpolation: it inserts a value into a selector, property name or string. The loop compiles to three .badge-* rules. Add a fourth entry to the map and a fourth class appears.

What the badge loop produces

Modules: @use and @forward

Modern Sass splits code into partials, files that start with an underscore (_tokens.scss). A partial is never compiled alone; other files load it with @use. Unlike the old global @import, @use loads a file once and puts its members behind a namespace, so names cannot collide silently.

SCSS
// _tokens.scss
$brand: #4f46e5 !default;
$space: 1rem;

@function space($n) { @return $space * $n; }
SCSS
// components/_button.scss
@use "../tokens" as t;

.btn {
  background: t.$brand;
  padding: t.space(0.5) t.space(1);
}
SCSS
// main.scss
@use "tokens" with ($brand: #0f766e);   // configure before first use
@use "base";
@use "components/button";

Three details are worth remembering:

  • The namespace defaults to the file name (tokens.$brand). Write as t to shorten it, or as * to drop it (rarely a good idea).
  • Names that begin with - or _ are private to their file.
  • @forward re-exports a file's members, so an index partial can gather a folder: @forward "button"; @forward "card";, and @use "components" loads the folder's _index.scss.

A common project layout, in the spirit of the layered approach from Organizing CSS:

TEXT
src/
  main.scss
  abstracts/   _tokens.scss  _mixins.scss  _functions.scss
  base/        _reset.scss   _typography.scss
  layout/      _grid.scss    _header.scss
  components/  _button.scss  _card.scss  _index.scss
  utilities/   _spacing.scss

Only things in abstracts/ produce no CSS by themselves; every other partial adds rules.

Placeholders and @extend

A placeholder selector starts with % and emits no CSS on its own. @extend then groups selectors onto the shared rule:

SCSS
%visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
}

.sr-only        { @extend %visually-hidden; }
.skip-link-text { @extend %visually-hidden; }

The output is one rule: .sr-only, .skip-link-text { position: absolute; ... }. This sounds ideal, but @extend can produce surprising selector lists and reorder rules when used across files. Many style guides prefer mixins or plain shared classes. Use @extend sparingly, and never on a selector with a long ancestor chain.

Pitfalls to avoid

  • Treating Sass variables like runtime variables. $brand cannot change in dark mode. Compile it into a custom property: --brand: #{$brand};. The #{} is required there so the value is inserted as-is.
  • Deep nesting. Four or five levels give selectors like .page .main .list .item a, which are hard to override. See specificity.
  • Bloat from mixins. Mixins copy; classes and custom properties share.
  • Debugging the wrong file. Turn source maps on in development, so DevTools shows _button.scss:12 rather than main.css:984.
  • Old tutorials. If a sample uses @import, / for division or global functions like darken(), it predates modules. Modern Sass has color.adjust() in sass:color, though color-mix() in native CSS (see Modern Color) often replaces it.

When Sass is still the right choice

Sass shines for loops that generate utility families or theme classes, for string-building BEM names with &__, for reusing one library's tokens across many files, and for large legacy codebases. If you only need variables, nesting, and file splitting, native CSS plus a bundler covers it. Both are good answers; what matters is that the team agrees on one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the browser receive when a project uses Sass?

    The compiler turns .scss into .css at build time. Browsers never see Sass syntax.
  2. 2. Why can't a Sass variable switch values for dark mode at runtime?

    Only custom properties live in the browser. A Sass variable is gone after compilation.
  3. 3. What is the advantage of @use over the old @import?

    @use avoids duplicated output and name collisions because each module's members are accessed through a namespace.
  4. 4. Which feature is Sass-only, with no equivalent in native CSS nesting?

    Native CSS can't append text to the parent selector, so &__title is Sass-only.
  5. 5. What is the main risk of including a large mixin many times?

    Mixins are expanded in place, so output size grows with every use. Shared classes or custom properties avoid that.

Summary

  • Sass compiles .scss into plain CSS; use npx sass --watch or a bundler, and enable source maps in development.
  • Variables with !default are compile-time and configurable; use custom properties for runtime theming.
  • Mixins take parameters, functions return values, maps plus @each generate families of rules, and #{} interpolates names.
  • @use and @forward replace @import; partials start with an underscore and members live behind namespaces.
  • Use %placeholder and @extend sparingly; keep nesting shallow.
  • Pick Sass when you need its loops or &__ names, and native CSS when variables, nesting and layers are enough.

Next: CSS Architecture: BEM, ITCSS and Utility Classes.