CSS Preprocessor — Explained with Examples
A CSS preprocessor extends CSS with variables, nesting, mixins, and functions, compiling to standard CSS for browser consumption.
CSS preprocessors — SASS/SCSS, LESS, and Stylus — add programming features to CSS. Key features: variables (reusable values like colors and fonts), nesting (selector hierarchy matching HTML structure), mixins (reusable style blocks with parameters), functions (computed values), and partials/imports (modular file organization). These features get compiled into standard CSS during the build step.
Think of a CSS preprocessor like a high-level recipe language versus raw ingredient lists. Instead of writing “2 cups flour, 1 cup sugar, 1 tsp vanilla” separately for every recipe (CSS), you define “basic_cake_mix” once and include it wherever needed (mixin). The kitchen (preprocessor compiler) converts your recipe language into actual measured ingredients (standard CSS).
Modern CSS has adopted some preprocessor features (native CSS variables with --custom-properties, calc()), but preprocessors still offer more powerful programming constructs.
// SCSS (Sassy CSS) example
// Variables
$primary-color: #3498db;
$font-stack: 'Inter', sans-serif;
$border-radius: 4px;
// Mixin
@mixin button-variant($bg, $color: white) {
background: $bg;
color: $color;
border-radius: $border-radius;
padding: 0.5rem 1rem;
border: none;
font-family: $font-stack;
&:hover {
background: darken($bg, 10%);
}
}
// Nesting
.card {
background: white;
border: 1px solid #eee;
padding: 1rem;
&__title {
font-size: 1.25rem;
color: $primary-color;
}
&__body {
margin-top: 0.5rem;
}
}
// Usage
.btn-primary {
@include button-variant($primary-color);
}
.btn-danger {
@include button-variant(#e74c3c);
}/* Compiled output */
.btn-primary {
background: #3498db;
color: white;
border-radius: 4px;
padding: 0.5rem 1rem;
border: none;
}
.btn-primary:hover {
background: #217dbb;
}Preprocessors are widely used in large projects to maintain consistent, DRY stylesheets. PostCSS (with plugins) offers an alternative approach: transforming standard CSS with JavaScript-based plugins.
CSS, PostCSS, Responsive Design, Mobile-First Design
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro