Sass Functions — Complete Guide
In this tutorial, you will learn about Sass Functions. We cover key concepts, practical examples, and best practices to help you master this topic.
Sass functions compute and return values for colors, calculations, and strings using built-in functions and custom @function definitions for reusable logic.
What You'll Learn
- Built-in color functions
- Math functions and calculations
- String and list functions
- Custom @function definitions
- Function vs mixin tradeoffs
- Using functions with maps
Why It Matters
- Functions compute dynamic values without manual calculation
- Color functions create palettes programmatically
- Custom functions encapsulate complex logic
- Functions reduce hard-coded magic numbers
Real-World Use
- A color palette darkens and lightens programmatically
- A fluid typography function calculates clamp values
- A spacing function converts a unit value to rem
- A z-index function manages layering order
flowchart LR A[Sass Functions] --> B[Built-in] A --> C[Custom @function] B --> D[Color: darken, lighten] B --> E[Math: ceil, floor, round] B --> F[List: nth, length, index] C --> G[Return computed value] G --> H[Use in any property]
Working with Functions
Code Example: Built-in Color Functions
// Color manipulation
$primary: #0066CC;
.element-1 {
background: darken($primary, 10%); // Darker by 10%
color: lighten($primary, 60%); // Lighter by 60%
}
.element-2 {
background: saturate($primary, 20%); // More saturated
color: desaturate($primary, 30%); // Less saturated
}
.element-3 {
background: rgba($primary, 0.5); // 50% opacity
color: mix($primary, #fff, 80%); // Mix with white (80% primary)
}
.element-4 {
background: complement($primary); // Opposite color on wheel
color: invert($primary); // Inverted color
}
.element-5 {
$lighter: lighten($primary, 20%);
$darker: darken($primary, 15%);
border-color: adjust-hue($primary, 30deg); // Shift hue by 30 degrees
}
// Creating a color palette
$colors: (
'primary': #0066CC,
'success': #28a745,
'danger': #dc3545
);
@each $name, $color in $colors {
.bg-#{$name} { background: $color; }
.bg-#{$name}-light { background: lighten($color, 30%); }
.bg-#{$name}-dark { background: darken($color, 15%); }
.text-#{$name} { color: $color; }
.border-#{$name} { border-color: $color; }
}
Expected output: Color functions generate lighter and darker variants automatically. A full color utility system (bg-primary, bg-primary-light, text-primary) is generated from just three base colors.
Code Example: Math and Number Functions
// Math functions
$base-font-size: 16px;
// Converting px to rem
@function rem($px) {
@return $px / $base-font-size * 1rem;
}
.element {
padding: rem(16); // 1rem
margin: rem(24); // 1.5rem
font-size: rem(14); // 0.875rem
}
// Fluid typography with clamp
@function fluid-size($min-size, $max-size, $min-vw: 320px, $max-vw: 1200px) {
$slope: ($max-size - $min-size) / ($max-vw - $min-vw);
$intercept: $min-size - $slope * $min-vw;
@return clamp(#{$min-size}, #{$intercept} + #{$slope * 100vw}, #{$max-size});
}
h1 {
font-size: fluid-size(2rem, 4rem);
}
h2 {
font-size: fluid-size(1.5rem, 2.5rem);
}
p {
font-size: fluid-size(1rem, 1.25rem);
}
// Unit conversion
@function strip-unit($value) {
@return $value / ($value * 0 + 1);
}
@function em($px, $base: 16px) {
@return strip-unit($px) / strip-unit($base) * 1em;
}
.element {
margin-bottom: em(24); // 1.5em
padding: em(16, 14px); // em with custom base
}
// Rounding
.element {
width: ceil(33.33%); // 34%
height: floor(33.33%); // 33%
opacity: round(0.555, 2); // 0.56
}
Expected output: The rem() function converts pixels to rems. The fluid-size() function generates clamp() values for responsive typography. Mathematical functions ensure precise calculations.
Code Example: List and Map Functions
// List functions
$fonts: 'Inter', 'Helvetica', Arial, sans-serif;
.element {
font-family: nth($fonts, 1); // 'Inter'
font-family: nth($fonts, -1); // sans-serif (last item)
}
// Check list
@if index($fonts, 'Helvetica') {
.alert { font-family: 'Helvetica'; }
}
// Loop with index
@for $i from 1 through length($fonts) {
.font-#{$i} {
font-family: nth($fonts, $i);
}
}
// Map functions
$breakpoints: (
'sm': 480px,
'md': 768px,
'lg': 1024px,
'xl': 1280px
);
@function bp($name) {
@if map-has-key($breakpoints, $name) {
@return map-get($breakpoints, $name);
} @else {
@error "Unknown breakpoint: #{$name}.";
}
}
@media (min-width: bp('md')) {
.container { max-width: 720px; }
}
// Map merge for themes
$light-theme: (
'bg': #fff,
'text': #333,
'primary': #0066CC
);
$dark-theme: map-merge($light-theme, (
'bg': #1a1a2e,
'text': #e0e0e0,
'primary': #4da6ff
));
@function theme($key, $theme: $light-theme) {
@if map-has-key($theme, $key) {
@return map-get($theme, $key);
}
@return null;
}
// Map keys for iteration
$theme-keys: map-keys($light-theme);
// Returns: ('bg', 'text', 'primary')
Expected output: Map functions create a centralized breakpoint and theme system. The bp() function looks up breakpoints by name. The theme() function retrieves values from theme maps.
Code Example: Custom Functions with Logic
// Contrast color function
@function contrast-color($bg) {
$lightness: lightness($bg);
@if $lightness > 60% {
@return #333; // Dark text on light bg
} @else {
@return #fff; // Light text on dark bg
}
}
// Z-index management
$elements: (
'modal': 1000,
'overlay': 900,
'nav': 800,
'header': 700,
'default': 1
);
@function z($element) {
@if map-has-key($elements, $element) {
@return map-get($elements, $element);
} @else {
@return map-get($elements, 'default');
}
}
// Responsive value
@function responsive($min, $max, $min-vw: 320px, $max-vw: 1200px) {
@return clamp(#{$min}, calc(#{$min} + (#{$max} - #{$min}) * ((100vw - #{$min-vw}) / (#{$max-vw} - #{$min-vw}))), #{$max});
}
// Usage
.btn {
background: $primary;
color: contrast-color($primary); // Returns #fff
z-index: z('nav'); // Returns 800
padding: responsive(1rem, 3rem); // Fluid padding
}
.modal {
z-index: z('modal'); // Returns 1000
background: #333;
color: contrast-color(#333); // Returns #fff
}
Expected output: Custom functions automate common decisions. contrast-color() chooses readable text color. z() centralizes z-index management. responsive() generates fluid values.
Common Mistakes
- Using functions when a variable would suffice — Functions add overhead. If the value is static, use a variable.
- Not using @return — Functions must explicitly return a value with @return. Without it, the function returns null.
- Forgetting to handle errors — Use @error, @warn, and @debug for invalid parameters. Functions should fail gracefully with clear messages.
- Overcomplicating with functions — Simple darken/lighten calls do not need a custom function. Keep functions focused on non-trivial logic.
- Not documenting return types — Functions should document what they return (unit, range, expected values).
- Side effects in functions — Functions should be pure (no side effects, same input always returns same output).
- Reinventing built-in functions — Check if Sass already has a function for what you need before writing a custom one.
Practice Questions
- How do you define a custom Sass function? @function name($params) { @return value; }
- What does the darken($color, $amount) function do? Decreases the lightness of a color by the given percentage.
- How do you retrieve a value from a Sass map? Use map-get($map, $key) to access values by key.
- What is the difference between a function and a mixin? A function returns a single value (used in property values). A mixin outputs CSS declarations (used with @include).
FAQ
Mini Project
Create a _functions.scss partial with 8 custom functions: (1) rem($px) for px-to-rem conversion, (2) em($px, $base) for px-to-em, (3) fluid-size($min, $max) for clamp-based fluid typography, (4) contrast-color($bg) for readable text color, (5) z($name) for z-index management from a map, (6) bp($name) for breakpoint lookups, (7) strip-unit($value) to remove units, and (8) theme($key, $theme) for theme value access. Build a sample page that uses all functions in different contexts (typography, colors, spacing, z-index, breakpoints, theming). Demonstrate how updating a single map value propagates through all functions.
What's Next
Continue with Lesson 7: Sass Extends and Inheritance to learn selector inheritance with @extend.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro