Performance: Why custom functions are useful
Custom functions in Sass affect CSS generation speed and final CSS size, impacting page load and render time.
@function lighten-primary($amount) { @return lighten(#3498db, $amount); } .button { background-color: lighten-primary(10%); } .card { background-color: lighten-primary(10%); }
$primary-color: #3498db; .button { background-color: lighten($primary-color, 10%); } .card { background-color: lighten($primary-color, 10%); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Repeated calculations inline | N/A | N/A | Larger CSS size increases paint time | [X] Bad |
| Custom function reuse | N/A | N/A | Smaller CSS size reduces paint time | [OK] Good |
@function, followed by the function name and parameters in parentheses.@return to send back a value.@function double($n) { @return $n * 2; }
.box { margin: double(10px); }double multiplies the input by 2, so double(10px) returns 20px.20px.@function add($a, $b) { return $a + $b; }@return keyword to return values, not plain return.return without @ causes a syntax error in Sass.Pass the test and this pattern moves unknown