Back to Curriculum

CSS Preprocessors: Sass/SCSS

📚 Lesson 16 of 16 ⏱️ 40 min

CSS Preprocessors: Sass/SCSS

40 min

CSS Preprocessors like Sass (Syntactically Awesome Style Sheets) extend CSS with features that don't exist in the native language yet, like nesting, mixins, inheritance, and mathematical operations.

**Nesting** allows you to nest your CSS selectors in a way that follows the same visual hierarchy of your HTML. **Mixins** let you create groups of CSS declarations that you can reuse throughout your site.

While modern CSS has adopted many features from preprocessors (like variables and nesting), Sass is still widely used in the industry for its powerful functions, loops, and partials (splitting CSS into small files).

The workflow involves writing `.scss` files and running a compiler (like the one built into Vite or Webpack) to turn them into standard `.css` files that the browser can understand.

Key Concepts

  • Preprocessors compile to CSS.
  • Nesting mirrors HTML structure.
  • Mixins are reusable code blocks.
  • Partials help organize code.
  • Mathematical operations in styles.

Learning Objectives

Master

  • Setting up a Sass workflow
  • Using Nesting effectively
  • Creating and using Mixins with arguments
  • Splitting code into Partials (@import/@use)

Develop

  • Code modularity and organization
  • DRY (Don't Repeat Yourself) principles
  • Advanced build tool configuration

Tips

  • Use SCSS syntax (brackets) over Sass syntax (indentation) for compatibility.
  • Don't nest more than 3 levels deep (specificity hell).
  • Use `&` to reference the parent selector (great for pseudo-classes).
  • Use partials (filenames starting with `_`) to organize components.

Common Pitfalls

  • Over-nesting, creating massive selectors like `.nav .list .item .link span`.
  • Using mixins for everything (bloats the output CSS).
  • Forgetting that the browser doesn't understand Sass (must compile).
  • Not using source maps (makes debugging compiled CSS hard).

Summary

  • Sass extends CSS with superpowers.
  • It improves organization and reusability.
  • Nesting and Mixins are key features.
  • It requires a compilation step.

Exercise

Write a simple SCSS snippet using variables and nesting, then show the compiled CSS.

// SCSS
$primary-color: #3498db;

.button {
  background: $primary-color;
  color: #fff;
  &:hover {
    background: darken($primary-color, 10%);
  }
}

/* Compiled CSS */
.button {
  background: #3498db;
  color: #fff;
}
.button:hover {
  background: #217dbb;
}

Exercise Tips

  • Create mixins for reusable code: @mixin flex-center { display: flex; justify-content: center; align-items: center; }.
  • Use @extend for inheritance: .button-primary { @extend .button; background: blue; }.
  • Try SCSS functions: lighten($color, 20%), rgba($color, 0.5).
  • Use @import to organize code into partials: @import 'variables', 'mixins';

Code Editor

Output