CSS Preprocessors

Sass basics, nesting, mixins.

Introduction

As CSS grows in size and complexity, maintaining it becomes difficult. CSS Preprocessors like Sass (Syntactically Awesome Stylesheets) solve this by adding features like variables, nesting, and mixins that standard CSS lacks.

In this chapter, you will learn:

  • Why specialized preprocessors are used in modern development
  • SCSS syntax basics (Variables, Nesting, Parent Selector)
  • Using Partials for file organization
  • Creating reusable code with Mixins and Functions

Sass Variables

Sass variables allow you to store values and reuse them throughout your stylesheet. They are compiled away, meaning they don't exist in the final CSS.

$primary-color: #007bff;
$border-radius: 4px;

.button {
  background-color: $primary-color;
  border-radius: $border-radius;
}

Nesting & Parent Selector

Nesting mimics HTML structure, making code readable. The & symbol refers to the parent selector.

/* SCSS */
.nav {
  ul {
    list-style: none;
    li { display: inline-block; }
  }
}

/* Parent Selector */
.button {
  &:hover { background: darkblue; }
  &--primary { background: blue; }
}

Mixins (Reusable Blocks)

Mixins let you group CSS declarations to avoid repetition.

@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  @include flex-center;
}

File Organization (Partials)

Split large SCSS files into smaller partials (prefixed with _) and import them.

// _variables.scss
$font-stack: Helvetica, sans-serif;

// main.scss
@import "variables";

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

Common Beginner Mistakes & Best Practices

Common Mistakes
  • Nesting too deeply (e.g., 5 levels deep)
  • Overusing @extend which bloats CSS
  • Using Sass for simple, small projects
Best Practices
  • Limit nesting to 2-3 levels
  • Use Mixins for logic, Placeholders for static styles
  • Structure files using the "7-1 Pattern"

Chapter Summary

In this chapter, you learned:

  • How Sass extends CSS with variables, nesting, and mixins.
  • The difference between SCSS syntax and indented Sass.
  • How to organize code using partials for scalability.
  • Best practices for maintaining a clean Sass codebase.

You now understand how Sass helps write cleaner, scalable, professional CSS.