A CSS preprocessor is a scripting language that extends the default capabilities of CSS. You write code in the preprocessor's syntax (we'll focus on SCSS, the most popular syntax for Sass), and a compiler converts it into regular CSS that browsers can understand.
1. Variables
Variables let you store values that you can reuse throughout your stylesheet. This is perfect for things like colors, fonts, or spacing units. In SCSS, variables start with a $ sign.
Code Snippet: Using Variables
SCSS:
SCSS
// Define variables
$primary-color: #3498db;
$base-font-size: 16px;
body {
  font-size: $base-font-size;
}
a {
  color: $primary-color;
  &:hover {
    color: darken($primary-color, 10%); // Sass has built-in functions!
  }
}
Compiled CSS:
CSS
body {
  font-size: 16px;
}
a {
  color: #3498db;
}
a:hover {
  color: #217dbb;
}
2. Nesting
Nesting allows you to write CSS selectors in a way that follows the same visual hierarchy as your HTML. This makes your code more organized and readable.
Code Snippet: Nested Selectors
SCSS:
SCSS
nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
    li {
      display: inline-block;
      a {
        display: block;
        padding: 6px 12px;
        text-decoration: none;
      }
    }
  }
}
Compiled CSS:
CSS
nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
nav ul li {
  display: inline-block;
}
nav ul li a {
  display: block;
  padding: 6px 12px;
  text-decoration: none;
}
3. Mixins
Mixins let you create reusable groups of CSS declarations. You can even pass arguments to them to make them more flexible. You define a mixin with @mixin and use it with @include.
Code Snippet: A Reusable Mixin
SCSS:
SCSS
// Define a mixin for creating flexbox containers
@mixin flex-center($direction: row) {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: $direction;
}
.container {
  @include flex-center(); // Uses the default 'row' direction
}
.sidebar {
  @include flex-center(column); // Passes 'column' as an argument
}
Compiled CSS:
CSS
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;
}
.sidebar {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}