SASS / SCSS
Beginner
1 min read
Built-in SASS Functions for Color and Math
Example
// ── sass:math and sass:color modules ─────────────────────────────────────────
@use 'sass:math';
@use 'sass:color';
// ── Math functions ────────────────────────────────────────────────────────────
$container-width : 1200px;
$gutter : 24px;
$columns : 12;
// Column width as a percentage
@function col-width($n) {
$total: $container-width - ($gutter * ($columns - 1));
@return math.div($total * $n, $columns) + ($gutter * ($n - 1));
}
.col-4 { width: math.percentage(math.div(4, 12)); } // 33.333%
.col-6 { width: math.percentage(math.div(6, 12)); } // 50%
.col-8 { width: math.percentage(math.div(8, 12)); } // 66.667%
// Golden ratio spacing scale
$phi : math.$e * 0.56 + 1; // approximation
$space: 1rem;
@for $i from 1 through 5 {
.space-#{$i} { margin-bottom: math.round($space * math.pow(1.5, $i - 1) * 100) / 100 * 1rem; }
}
// ── Color functions ───────────────────────────────────────────────────────────
$base: #3498db;
// Palette generation from a single base color
$color-100: color.adjust($base, $lightness: 40%); // very light
$color-300: color.adjust($base, $lightness: 20%); // light
$color-500: $base; // base
$color-700: color.adjust($base, $lightness: -15%); // dark
$color-900: color.adjust($base, $lightness: -30%); // very dark
.palette-demo {
&-100 { background: $color-100; }
&-300 { background: $color-300; }
&-500 { background: $color-500; }
&-700 { background: $color-700; }
&-900 { background: $color-900; }
}
// color.mix for tints and shades
$tint : color.mix(#fff, $base, 70%); // 70% white mixed in
$shade : color.mix(#000, $base, 30%); // 30% black mixed in
Related Resources
SASS / SCSS Reference
Complete tag & property list
SASS / SCSS How-To Guides
Step-by-step practical guides
SASS / SCSS Exercises
Practice what you've learned
More in SASS / SCSS