Sass — Functions
Custom functions
@function spacing($multiplier) {
@return $multiplier * 8px;
}
.container {
padding: spacing(2); // 16px
margin: spacing(3); // 24px
}
Built-in math functions
@use 'sass:math';
.width {
width: math.percentage(1 / 3); // 33.3333%
}
.rounded {
border-radius: math.round(4.6px); // 5px
}
.clamp {
width: math.max(200px, 50%); // max of both
height: math.min(100vh, 600px); // min of both
}
Color functions
$primary: #3498db;
.button {
background: $primary;
&:hover { background: darken($primary, 10%); }
&:active { background: darken($primary, 20%); }
&:disabled { background: lighten($primary, 30%); }
}
.border {
border-color: darken($primary, 20%);
}
String functions
$name: 'button';
.className {
&::before {
content: str-insert($name, '-', 7);
}
}
// str-length, str-upcase, str-downcase, str-slice
List functions
$fonts: Arial, Helvetica, sans-serif;
body {
font-family: $fonts;
font-size: list.nth($fonts, 1); // Arial
}
// list.length, list.append, list.join, list.index
Map functions
$colors: (
primary: #3498db,
secondary: #2ecc71
);
.button {
background: map-get($colors, primary);
}
// Check if key exists
@each $key, $value in $colors {
.text-#{$key} {
color: $value;
}
}
Random function
.item {
animation-delay: random() * 2s;
}
Type checking
$var: 10;
@if type-of($var) == 'number' {
.box { width: $var * 2px; }
}
Mini Practice
- Create a spacing function with multiplier
- Build a color shade generator function
- Use map-get for a design token system
- Create a function that returns responsive font sizes
Up Next
Continue with Operators — arithmetic and comparison operators.
Related Topics
Frequently Asked Questions about Functions
What is Functions in Sass?
Functions is a fundamental concept in Sass. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Functions?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Functions.
Why is Functions important in Sass?
Functions is essential for Sass development. Understanding this concept will help you write better code and solve real-world problems more effectively.