On this page
CSS Preprocessors (Sass)
What is Sass?
Sass (Syntactically Awesome Style Sheets) extends CSS with variables, nesting, mixins, and more. It compiles to standard CSS.
Two syntaxes: SCSS (.scss, CSS-compatible) and Sass (.sass, indentation-based). SCSS is more common.
Variables
$primary: #007bff;
$spacing: 1rem;
$font-stack: 'Inter', sans-serif;
.button {
background: $primary;
padding: $spacing;
font-family: $font-stack;
}
Modern alternative: CSS custom properties (--primary) work natively without compilation.
Nesting
.nav {
display: flex;
&__item {
padding: 0.5rem 1rem;
&:hover {
background: #f0f0f0;
}
&--active {
font-weight: bold;
}
}
}
Avoid nesting more than 3 levels deep — it increases specificity and makes overrides harder.
Mixins
Reusable style blocks with parameters:
@mixin flex-center {
display: flex;
justify-content: center;
align-items: center;
}
@mixin responsive($breakpoint) {
@media (min-width: $breakpoint) {
@content;
}
}
.hero {
@include flex-center;
min-height: 100vh;
@include responsive(768px) {
min-height: 60vh;
}
}
Partials and Imports
Split styles into modules:
// _variables.scss
$primary: #007bff;
// _buttons.scss
@import 'variables';
.button { background: $primary; }
// main.scss
@import 'variables';
@import 'buttons';
Use @use instead of @import in modern Sass (avoids global namespace pollution):
@use 'variables' as vars;
.button { background: vars.$primary; }
Functions
@function rem($px) {
@return #{$px / 16}rem;
}
.container {
padding: rem(24); // 1.5rem
}
Setup
npm install -D sass
npx sass scss/main.scss css/main.css --watch
Sass remains widely used in legacy projects and design systems. For new projects, evaluate whether native CSS features (variables, nesting in modern browsers) are sufficient.