SASS / SCSS
Beginner
1 min read
Writing Custom @function Definitions
Example
// ── Custom @function examples ─────────────────────────────────────────────────
@use 'sass:math';
@use 'sass:string';
// Convert pixels to rem based on a configurable base font size
$base-font-size: 16px;
@function rem($px) {
@return math.div($px, $base-font-size) * 1rem;
}
// Convert pixels to em based on a parent size
@function em($px, $parent: 16px) {
@return math.div($px, $parent) * 1em;
}
// Clamp a value between a min and max
@function clamp-value($value, $min, $max) {
@return min(max($value, $min), $max);
}
// Build a CSS custom property reference string
@function token($name) {
@return var(--#{$name});
}
// Determine whether text on a given background should be light or dark
@function contrast-color($bg, $light: #fff, $dark: #222) {
$lightness: lightness($bg);
@return if($lightness > 50%, $dark, $light);
}
// ── Using the functions ───────────────────────────────────────────────────────
h1 { font-size: rem(36px); } // → 2.25rem
h2 { font-size: rem(28px); } // → 1.75rem
p { font-size: rem(16px); } // → 1rem
.caption { font-size: em(13px, 16px); } // → 0.8125em
$brand: #3498db;
.badge {
background: $brand;
color : contrast-color($brand); // #fff (brand is dark enough)
padding : rem(4px) rem(10px);
border-radius: rem(12px);
}
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