CSS Preprocessors (Sass/SCSS)
Sass (SCSS) extends CSS with variables, nesting, mixins, functions, and imports — features that make CSS more maintainable. While native CSS has adopted many of these features (variables, nesting), Sass is still widely used in production codebases.
Sass/SCSS Features
- Variables — $primary: #667eea; (Sass) vs --primary: #667eea; (CSS). Sass compiles at build time
- Nesting — .card { &__title { } &:hover { } }. Native CSS now supports this too
- Mixins — @mixin flex-center { display: flex; align-items: center; justify-content: center; } Reusable style blocks
- @include — @include flex-center; applies the mixin's styles. Like CSS functions
- Partials — _variables.scss, _mixins.scss. Underscore = partial, not compiled standalone
- @extend — .btn-primary { @extend .btn; } inherits all styles of .btn. Use sparingly
- Sass vs CSS — Sass still wins for: mixins, @extend, math functions, control flow (@if/@for). CSS is catching up fast
Sass/SCSS Code
// Variables
$primary: #667eea;
$radius: 12px;
$shadow: 0 2px 8px rgba(0,0,0,0.08);
// Mixin
@mixin flex-center {
display: flex;
align-items: center;
justify-content: center;
}
@mixin responsive($breakpoint) {
@if $breakpoint == tablet { @media (min-width: 768px) { @content; } }
@if $breakpoint == desktop { @media (min-width: 1024px) { @content; } }
}
// Usage with nesting
.card {
background: white;
border-radius: $radius;
box-shadow: $shadow;
&__title {
color: darken($primary, 10%);
font-weight: 600;
}
&__body {
padding: 20px;
}
&--featured {
border: 2px solid $primary;
}
@include responsive(tablet) {
padding: 32px;
}
}
.hero {
@include flex-center;
min-height: 100vh;
}Tip
Sass mixins remain uniquely powerful. @mixin responsive($bp) { @media (min-width: $bp) { @content } } lets you write .card { @include responsive(768px) { flex-direction: row } }. Native CSS can't do parameterized reusable blocks like this.
Every element follows the box model — content + padding + border + margin
Common Mistake
Over-using @extend in Sass. @extend merges selectors, creating unexpected CSS output and making debugging difficult. Prefer mixins (@include) for reusable styles — they generate predictable, independent CSS blocks.
Practice Task
Write a Sass component: (1) Define $primary and $radius variables, (2) Create a @mixin flex-center and @mixin responsive(tablet/desktop), (3) Build a .card using nesting, variables, and the responsive mixin, (4) Compare the compiled CSS output.
Quick Quiz
Key Takeaways
- Sass (SCSS) extends CSS with variables, nesting, mixins, functions, and imports — features that make CSS more maintainable.
- Variables — $primary: #667eea; (Sass) vs --primary: #667eea; (CSS). Sass compiles at build time
- Nesting — .card { &__title { } &:hover { } }. Native CSS now supports this too
- Mixins — @mixin flex-center { display: flex; align-items: center; justify-content: center; } Reusable style blocks