0
0
SASSmarkup~15 mins

Why custom functions are useful in SASS - Why It Works This Way

Choose your learning style9 modes available
Overview - Why custom functions are useful
What is it?
Custom functions in Sass are small pieces of code you write to perform specific tasks or calculations. They help you reuse code and keep your stylesheets clean and organized. Instead of repeating the same code, you write a function once and use it wherever needed. This makes your CSS easier to manage and update.
Why it matters
Without custom functions, you would have to write the same calculations or style rules over and over, which wastes time and can cause mistakes. Custom functions save effort and reduce errors by automating repetitive tasks. They make your stylesheets smarter and more flexible, so you can quickly adapt designs without rewriting lots of code.
Where it fits
Before learning custom functions, you should understand basic Sass syntax, variables, and mixins. After mastering custom functions, you can explore advanced Sass features like control directives (if, for loops) and creating libraries of reusable styles.
Mental Model
Core Idea
Custom functions let you package repeated style logic into reusable blocks that return values, making your stylesheets smarter and easier to maintain.
Think of it like...
It's like having a kitchen gadget that peels apples perfectly every time, so you don't have to peel each apple by hand. You just use the gadget whenever you need peeled apples.
┌───────────────────────────────┐
│          Custom Function       │
│  ┌───────────────┐            │
│  │ Input values  │            │
│  └──────┬────────┘            │
│         │                     │
│  ┌──────▼────────┐            │
│  │  Function     │            │
│  │  Logic/Code   │            │
│  └──────┬────────┘            │
│         │                     │
│  ┌──────▼────────┐            │
│  │  Output value │            │
│  └───────────────┘            │
└───────────────────────────────┘
Build-Up - 6 Steps
1
FoundationWhat are Sass custom functions
🤔
Concept: Introducing the idea of writing your own functions in Sass to return values.
In Sass, you can write custom functions using the @function directive. These functions take inputs, perform calculations or logic, and return a value. For example, a function can calculate a color shade or convert units.
Result
You can create reusable code blocks that return values to use in your styles.
Understanding that Sass functions return values helps you see how they can replace repeated calculations and keep your code DRY (Don't Repeat Yourself).
2
FoundationBasic syntax of custom functions
🤔
Concept: Learning the structure of a Sass function with parameters and return statement.
A Sass function starts with @function followed by the name and parameters in parentheses. Inside, you write Sass code and end with @return to send back a value. Example: @function double($number) { @return $number * 2; }
Result
You can call double(5) in your styles and get 10 as the result.
Knowing the syntax lets you write your own functions to automate simple or complex calculations.
3
IntermediateUsing functions to simplify calculations
🤔Before reading on: do you think functions can only return numbers, or can they return colors and other types? Commit to your answer.
Concept: Functions can return any Sass value, including colors, strings, or lists, not just numbers.
Sass functions are flexible. For example, you can write a function to lighten a color by a percentage: @function lighten-color($color, $amount) { @return lighten($color, $amount); } This lets you reuse color adjustments easily.
Result
You get consistent color variations by calling your function with different inputs.
Understanding that functions can return various types expands their usefulness beyond math to styling logic.
4
IntermediateCombining functions with variables and mixins
🤔Before reading on: do you think functions can replace mixins, or do they serve different purposes? Commit to your answer.
Concept: Functions return values, while mixins output CSS rules; they work together to make styles dynamic and reusable.
You can use a function inside a mixin to calculate values dynamically. For example: @mixin button($color) { background-color: lighten-color($color, 20%); color: white; } This mixin uses the lighten-color function to set the background.
Result
Your styles become more flexible and easier to update by combining functions and mixins.
Knowing the difference and synergy between functions and mixins helps you organize your Sass code effectively.
5
AdvancedHandling complex logic inside functions
🤔Before reading on: do you think Sass functions can use if-else logic and loops? Commit to your answer.
Concept: Sass functions can include control directives like @if and @for to handle complex decisions and calculations.
You can write functions that change output based on conditions: @function responsive-font($size) { @if $size == small { @return 12px; } @else if $size == medium { @return 16px; } @else { @return 20px; } } This function returns different font sizes based on input.
Result
Functions can adapt their output dynamically, making your styles smarter.
Understanding control flow inside functions unlocks powerful ways to automate style decisions.
6
ExpertPerformance and maintainability considerations
🤔Before reading on: do you think overusing functions can slow down Sass compilation or make code harder to read? Commit to your answer.
Concept: While functions add power, excessive or complex functions can slow compilation and reduce code clarity if not managed well.
In large projects, too many nested or heavy functions can increase compile time. Also, unclear function names or logic can confuse team members. Experts balance function use with readability and performance, sometimes caching results or simplifying logic.
Result
You write efficient, maintainable Sass that compiles quickly and is easy for teams to understand.
Knowing the tradeoffs helps you write professional Sass code that scales well in real projects.
Under the Hood
When Sass compiles your styles, it processes custom functions by running their code with given inputs and replacing the function call with the returned value. This happens before generating the final CSS. The Sass compiler evaluates the function logic in memory, allowing dynamic calculations during compilation.
Why designed this way?
Sass was designed to extend CSS with programming features while keeping output as plain CSS. Custom functions let developers write reusable logic without bloating the final CSS. This design balances power and simplicity, avoiding runtime overhead by doing all calculations at compile time.
Sass Source Code
      │
      ▼
┌─────────────────────┐
│  Sass Compiler      │
│  ┌───────────────┐  │
│  │ Custom Funcs  │  │
│  │  Evaluated    │  │
│  └──────┬────────┘  │
│         │           │
│  ┌──────▼────────┐  │
│  │  Output CSS   │  │
│  └──────────────┘  │
└─────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: do you think Sass functions can generate CSS rules directly? Commit to yes or no.
Common Belief:Sass functions can output CSS rules like mixins do.
Tap to reveal reality
Reality:Sass functions only return values; they cannot output CSS rules directly. Mixins are used for outputting CSS blocks.
Why it matters:Confusing functions with mixins can lead to errors and unexpected results in your stylesheets.
Quick: do you think custom functions run in the browser? Commit to yes or no.
Common Belief:Custom functions run in the browser when the page loads.
Tap to reveal reality
Reality:Custom functions run only during Sass compilation on your computer or build server, not in the browser.
Why it matters:Expecting runtime behavior can cause confusion about when styles update and how dynamic your CSS can be.
Quick: do you think you can use JavaScript or other languages inside Sass functions? Commit to yes or no.
Common Belief:You can write Sass functions using JavaScript or other programming languages.
Tap to reveal reality
Reality:Sass functions must be written in Sass syntax; you cannot embed JavaScript or other languages inside them.
Why it matters:Trying to mix languages leads to syntax errors and misunderstanding of Sass capabilities.
Quick: do you think using many nested functions always improves your Sass code? Commit to yes or no.
Common Belief:More nested functions always make Sass code better and more reusable.
Tap to reveal reality
Reality:Excessive nesting can make code harder to read and slow down compilation.
Why it matters:Overusing functions without care can reduce maintainability and performance.
Expert Zone
1
Functions can be pure (always return the same output for the same input) which helps caching and predictability.
2
Sass functions cannot access CSS properties or selectors directly; they only work with values, which limits some dynamic styling but keeps compilation simple.
3
You can create libraries of custom functions shared across projects to enforce design consistency and speed up development.
When NOT to use
Avoid using custom functions when you need to output multiple CSS rules or complex selectors; use mixins instead. Also, for runtime dynamic styles based on user interaction, use JavaScript rather than Sass functions.
Production Patterns
In production, teams use custom functions to centralize calculations like spacing scales, color manipulations, or responsive breakpoints. Functions are combined with variables and mixins to build scalable, maintainable design systems.
Connections
Mathematical Functions
Custom Sass functions are similar to math functions that take inputs and return outputs.
Understanding math functions helps grasp how Sass functions process inputs to produce consistent results.
Software DRY Principle
Custom functions embody the DRY (Don't Repeat Yourself) principle by reusing code.
Knowing DRY helps appreciate why functions reduce errors and save time in styling.
Factory Machines in Manufacturing
Custom functions are like factory machines that take raw materials (inputs) and produce parts (outputs) repeatedly.
Seeing functions as machines clarifies how they automate repetitive tasks efficiently.
Common Pitfalls
#1Trying to output CSS rules inside a function.
Wrong approach:@function make-red() { color: red; }
Correct approach:@mixin make-red() { color: red; }
Root cause:Confusing functions (which return values) with mixins (which output CSS rules).
#2Calling a function without required arguments.
Wrong approach:width: double();
Correct approach:width: double(10px);
Root cause:Not providing necessary parameters causes errors or unexpected results.
#3Using complex logic that slows compilation.
Wrong approach:@function heavy-calc($n) { @for $i from 1 through $n { // complex nested loops } @return $n; }
Correct approach:Simplify logic or pre-calculate values outside Sass to keep compilation fast.
Root cause:Overusing loops and heavy calculations inside functions increases compile time.
Key Takeaways
Custom functions in Sass let you write reusable code that returns values to simplify your stylesheets.
They help automate calculations and style logic, making your CSS easier to maintain and update.
Functions differ from mixins because they return values instead of outputting CSS rules directly.
Using control flow inside functions unlocks powerful dynamic styling possibilities during compilation.
Balancing function complexity is key to keeping your Sass code efficient and readable in real projects.