Episode 1 — Fundamentals / 1.7 — Working With SASS

1.7 — Working With SASS: Quick Revision

Compact cheat sheet. Print-friendly.

How to use this material (instructions)

  1. Skim top-to-bottom in one pass before interviews or exams.
  2. If a row feels fuzzy — reopen the matching lesson: README.md1.7.a1.7.i.
  3. Drills1.7-Exercise-Questions.md.
  4. Polished answers1.7-Interview-Questions.md.

1.7.a What Is SASS

Core Concept

You write SCSS ──► Compiler (Dart Sass) ──► Plain CSS ──► Browser
                      (build time)                      (zero runtime cost)

Key Features

FeatureOne-liner
Variables$name: value; — single source of truth for colors, spacing, fonts
NestingWrite child selectors inside parent blocks; & for pseudo-classes
MixinsReusable declaration blocks — @mixin / @include
FunctionsCompute and @return values — used inline in properties
Partials_file.scss — split code into small files, combine at build
OperatorsMath, comparison, logical operators inside stylesheets
Control flow@if, @for, @each, @while — generate CSS programmatically
Inheritance@extend / %placeholder — group selectors sharing rules

Compiler Timeline

YearEvent
2006SASS created (Ruby, indented syntax)
2009SCSS syntax introduced
2016Dart Sass becomes reference implementation
2019@use / @forward module system
2022LibSass and Node Sass deprecated

1.7.b SCSS vs SASS Syntax & Setup

Syntax Comparison

SCSSIndented SASS
Braces{ } requiredNone — indentation
SemicolonsRequiredNone — newlines
CSS supersetYesNo
File extension.scss.sass
Usage~95% of projectsLegacy only

Setup Commands

npm install --save-dev sass                    # install Dart Sass
npx sass src/scss:dist/css --watch             # watch mode
npx sass src/scss:dist/css --style=compressed  # production build

Folder Structure (Simplified)

src/scss/
  abstracts/    ← variables, mixins, functions
  base/         ← reset, typography
  components/   ← buttons, cards, modals
  layout/       ← header, footer, grid
  pages/        ← page-specific styles
  main.scss     ← entry point

1.7.c Variables & Nesting

Variables

$primary: #3b82f6;       // color
$spacing: 1rem;          // number
$font: 'Inter', sans;    // string (list)
$debug: false;           // boolean
$nothing: null;          // null → omits property

Data Types

Numbers · Strings · Colors · Booleans · Null · Lists · Maps

Variable Flags

FlagEffect
!defaultUse value only if not already defined
!globalForce local variable to global scope (avoid)

Nesting & &

.btn {
  background: $primary;
  &:hover    { background: darken($primary, 10%); }   // pseudo-class
  &--large   { padding: 1rem 2rem; }                   // BEM modifier
  &__icon    { margin-right: 0.5rem; }                  // BEM element
}

Rule: Max 3 levels deep.

SCSS Variables vs CSS Custom Properties

Dimension$var--var
ResolvedCompile timeRuntime
CascadeNoYes
JS accessNoYes
DynamicNo (recompile)Yes

1.7.d Partials & Imports

Partials

  • File name starts with _: _variables.scss
  • Never compiled alone — pulled in by entry file

@use (Modern)

@use 'abstracts/variables';              // namespace: variables
@use 'abstracts/variables' as vars;      // custom namespace
@use 'abstracts/variables' as *;         // no namespace (use sparingly)

@forward (Re-export)

// abstracts/_index.scss
@forward 'variables';
@forward 'mixins';
@forward 'functions' hide _private;

@import (Deprecated)

@import problem@use fix
Global scope pollutionNamespacing
Duplicate outputSingle-load guarantee
No visibility control@forward show/hide

7-1 Pattern

abstracts/ · base/ · components/ · layout/ · pages/ · themes/ · vendors/ + main.scss


1.7.e Mixins

Syntax

@mixin name($arg1, $arg2: default) {
  property: $arg1;
  other: $arg2;
}

.element { @include name(value1); }

@content Blocks

@mixin breakpoint($bp) {
  @media (min-width: $bp) { @content; }
}

.sidebar {
  width: 100%;
  @include breakpoint(768px) { width: 250px; }
}

Common Mixins

MixinPurpose
flex-centerFlexbox centering (3 properties)
breakpoint($name)Responsive media query wrapper
truncate($lines)Text overflow ellipsis
visually-hiddenAccessible screen-reader-only hide

Mixin vs Function vs Extend

MixinFunctionExtend
ProducesDeclarationsValueGrouped selectors
ArgumentsYesYesNo
@contentYesNoNo
Media queriesWorksN/AFails

1.7.f Inheritance & Extends

Placeholder Selectors

%btn-base {
  padding: 0.5rem 1rem;
  border: none;
  cursor: pointer;
}

.btn-primary { @extend %btn-base; background: blue; }
.btn-danger  { @extend %btn-base; background: red; }
// Output: .btn-primary, .btn-danger { padding: … }

Pitfalls

PitfallCause
Unexpected selectorsExtending a class extends it in all compound selectors
Media query errorCannot extend across @media boundaries
Selector bloatMany extends → enormous comma-separated selectors

Default choice: Mixins. Use extend with %placeholder only for small, static shared bases.


1.7.g Functions & Operators

Custom Function

@use 'sass:math';

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

h1 { font-size: rem(32); }   // 2rem

Operators

TypeOperators
Arithmetic+, -, *, math.div(), %
Comparison==, !=, <, >, <=, >=
Logicaland, or, not
String+ (concatenation), #{} (interpolation)

Built-in Modules

ModuleKey functions
sass:mathmath.div(), math.round(), math.ceil(), math.clamp(), math.abs()
sass:colorcolor.adjust(), color.scale(), color.change(), color.mix()
sass:listlist.append(), list.nth(), list.length(), list.join()
sass:mapmap.get(), map.merge(), map.keys(), map.values(), map.has-key()
sass:stringstring.to-upper-case(), string.slice(), string.index()
sass:metameta.type-of(), meta.inspect()

1.7.h Control Directives

@if / @else

@if $theme == 'dark' {
  background: #1e293b;
} @else {
  background: #fff;
}

@for

@for $i from 1 through 8 {
  .mt-#{$i} { margin-top: $i * 0.25rem; }
}
// through = inclusive; to = exclusive

@each (Lists & Maps)

$colors: ('primary': #3b82f6, 'danger': #ef4444);

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

@while (Rare)

$i: 6;
@while $i > 0 {
  .w-#{$i} { width: $i * 100px; }
  $i: $i - 1;
}
// Danger: infinite loop if condition never becomes false

Best Practices

  • Prefer @each for named items, @for for numeric sequences
  • Always check compiled CSS size — loops can explode
  • Use maps as configuration data for @each generation

1.7.i Color Functions

Legacy (Global)

FunctionEffect
lighten($c, %)Increase lightness
darken($c, %)Decrease lightness
saturate($c, %)Increase saturation
desaturate($c, %)Decrease saturation
complement($c)180° hue rotation
mix($a, $b, %)Blend two colors
rgba($c, alpha)Set transparency

Modern (sass:color)

FunctionBehavior
color.adjust($c, $lightness: 20%)Shift by fixed amount
color.scale($c, $lightness: 20%)Shift proportionally (toward max/min)
color.change($c, $lightness: 90%)Set absolute value
color.mix($a, $b, 50%)Blend (weight = % of first color)

Palette Generation

@use 'sass:color';

$base: #3b82f6;
:root {
  --blue-100: #{color.scale($base, $lightness: 80%)};
  --blue-300: #{color.scale($base, $lightness: 40%)};
  --blue-500: #{$base};
  --blue-700: #{color.scale($base, $lightness: -40%)};
  --blue-900: #{color.scale($base, $lightness: -70%)};
}

Accessibility

  • Generated colors may fail WCAG contrast — always verify with a contrast checker
  • color.scale() is safer than color.adjust() for avoiding extreme results
  • Define text colors explicitly for each shade — do not assume white/black will contrast

One-liner definitions (25+ terms)

TermOne-liner
SASSCSS preprocessor — adds variables, nesting, mixins, functions, logic; compiles to CSS.
SCSSCSS-compatible SASS syntax using curly braces and semicolons.
Dart SassThe only actively maintained SASS compiler (npm package: sass).
PartialSCSS file starting with _ — not compiled alone, imported by entry file.
@useModern import — loads file once, creates namespace, declares dependency.
@forwardRe-exports members from one file through another (folder API).
@importDeprecated import — global scope, duplicate output, no namespacing.
$variableCompile-time value — resolved before CSS reaches the browser.
!defaultSet value only if not already defined — lets consumers override library defaults.
NestingWriting child selectors inside parent blocks to mirror HTML structure.
&Parent selector reference — used for pseudo-classes, BEM, modifiers.
@mixinDefines a reusable block of CSS declarations.
@includeStamps a mixin's declarations into a rule set.
@contentPlaceholder inside a mixin for injected CSS blocks.
@extendShares rules by grouping selectors in compiled CSS.
%placeholderAbstract selector — exists only to be extended, no standalone output.
@functionComputes and returns a value via @return.
@returnSends a value back from a function — required in every code path.
math.div()Division function replacing deprecated / operator.
#{}String interpolation — embeds variables in selectors, properties, media queries.
@ifConditional — emit CSS only when condition is true.
@forNumeric loop — through is inclusive, to is exclusive.
@eachIterate lists or maps — most versatile loop for named data.
7-1 patternSCSS architecture: 7 folders + 1 entry file.
Source map.css.map file linking compiled CSS back to original SCSS lines in DevTools.
color.scale()Proportional color adjustment — safer than fixed-amount color.adjust().
color.mix()Blend two colors by weight — useful for tints and shades.

Master workflow — The SASS Development Stack

  1. Install Dart Sass: npm install --save-dev sass.
  2. Organize files: abstracts (variables, mixins, functions) → base → components → layout → pages.
  3. Wire files with @use and @forward; create _index.scss per folder.
  4. Write SCSS: $variables for values, @mixin for reusable blocks, @function for computed values.
  5. Nest sparingly (max 3 levels); use & for pseudo-classes and BEM.
  6. Generate utilities with @each / @for loops from maps.
  7. Manipulate colors with color.scale() / color.mix() — verify contrast.
  8. Compile with --watch in development, --style=compressed --no-source-map for production.
  9. Post-process with Autoprefixer, PurgeCSS, and cssnano in the build pipeline.
  10. Verify — diff compiled CSS, check file size, test accessibility.

End of 1.7 quick revision.