Sub topic 14
Built-in modules such as sass:math and sass:map
This chapter assumes you can write Sass variables, maps, and functions, and that you know how @use namespaces work from the chapter on partials, @use and @forward. Built-in modules use the same mechanism. The only difference is that Dart Sass supplies them, so you don't need a file.
What a built-in module is
A built-in module is a set of functions and a few variables that ship with Dart Sass. You load one with @use and a URL that starts with sass:. There is no file on disk, and Sass resolves the name internally.
Dart Sass provides these modules:
| Module | Typical use |
|---|---|
| `sass:math` | Division, rounding, percentages, powers, unit checks |
| `sass:map` | Reading, merging, and changing maps |
| `sass:list` | Lengths, indexes, appending, joining |
| `sass:string` | Case changes, slicing, unquoting |
| `sass:color` | Adjusting and scaling colors |
| `sass:selector` | Building and testing selectors |
| `sass:meta` | Inspecting values, checking for functions, loading CSS |
Loading rules
Built-in modules follow the same rules as your own modules.
@userules must come before any style rules. Only@forwardand variable declarations may precede them.- The namespace is the last part of the URL, so
sass:mathgives youmath. - You can rename the namespace with
as, as in@use 'sass:math' as m;. as *puts the members in the global scope. Avoid it for built-ins, because short names likeminormaxthen clash with CSS functions.- Each module is loaded once per file. Another file that needs
mathmust write its own@use.
@use 'sass:math';
@use 'sass:map';
.box {
width: math.percentage(math.div(1, 4));
}sass:math
Plain / is no longer division in Sass, because it also appears in CSS values such as font: 12px/1.5. Use math.div for division.
@use 'sass:math';
$base: 16px;
.column {
width: math.percentage(math.div(1, 3));
padding: math.div($base, 2);
margin: math.round(math.div($base, 3));
font-size: math.max(14px, math.div($base, 1.5));
}This compiles to:
.column {
width: 33.3333333333%;
padding: 8px;
margin: 5px;
font-size: 14px;
}math.div(16px, 3) is 5.3333333333px, and math.round turns it into 5px. Sass keeps the unit through all of this.
These are the functions and variables you will use most:
math.div($a, $b)divides two numbers. Units are divided too, somath.div(10px, 2px)is the unitless5.math.round,math.floor,math.ceil, andmath.abschange a number and keep its unit.math.min,math.max, andmath.clamp($min, $number, $max)compare numbers. Their arguments need compatible units.math.percentage($number)turns a unitless number into a percentage.math.pow,math.sqrt, andmath.logdo exponent and root work.math.$piandmath.$eare constants.math.unit,math.is-unitless, andmath.compatiblereport on units.
The +, -, *, and % operators still work without the module, so you only need sass:math when you want one of its functions.
sass:map
Maps are immutable in Sass. Every sass:map function returns a new map and leaves the original unchanged. If you want the change to last, assign the result to a variable.
@use 'sass:map';
$theme: (
colors: (primary: #3366cc, danger: #cc3333),
spacing: (sm: 4px, md: 8px, lg: 16px)
);
.alert {
color: map.get($theme, colors, danger);
padding: map.get($theme, spacing, md);
}
$dark: map.deep-merge($theme, (colors: (primary: #6699ff)));
.alert-dark {
color: map.get($dark, colors, primary);
background: map.get($dark, colors, danger);
}This compiles to:
.alert {
color: #cc3333;
padding: 8px;
}
.alert-dark {
color: #6699ff;
background: #cc3333;
}map.get($theme, colors, danger) walks down through nested maps, so you don't need to nest calls. map.deep-merge merges the nested colors map, so danger survives. A plain map.merge would replace the whole colors map with (primary: #6699ff), and danger would be lost.
Other sass:map functions:
map.has-key($map, $keys...)returnstrueorfalse, and it also accepts a path of keys.map.keys($map)andmap.values($map)return lists.map.set($map, $keys..., $value)adds or replaces one entry, such asmap.set($theme, spacing, xl, 32px).map.remove($map, $keys...)drops top-level keys, andmap.deep-removeremoves a nested key.
Failing loudly on a missing key
map.get returns null when the key is missing. Sass leaves out any property whose value is null, so a typo in a token name produces no error. The property just silently disappears from the CSS. Wrap the lookup in a function that checks first.
@use 'sass:map';
$spacing: (sm: 4px, md: 8px, lg: 16px);
@function space($name) {
@if not map.has-key($spacing, $name) {
@error "Unknown spacing token: #{$name}. Use one of: #{map.keys($spacing)}.";
}
@return map.get($spacing, $name);
}
.card {
padding: space(md);
}If you write space(xl), compilation stops and the message names the bad token and lists the valid ones. This is the usual pattern for design token maps.
Other modules in practice
The other modules work the same way, and you will mostly call them from your own functions and mixins.
@use 'sass:color';
@use 'sass:list';
@use 'sass:string';
$font-stack: 'Inter', 'Helvetica Neue', sans-serif;
.btn {
background: color.adjust(#3366cc, $lightness: -10%);
font-family: $font-stack;
--font-count: #{list.length($font-stack)};
--label: #{string.to-upper-case('buy')};
}color.adjust shifts a channel by a fixed amount, here lowering lightness by 10 points. color.scale moves a channel by a percentage of the room it has left, so it never overshoots. Use scale for hover and disabled states that must work on both light and dark colors.
sass:meta is for tooling code. meta.type-of($value) tells you what kind of value you hold. meta.inspect($value) turns any value into a string for debugging. meta.function-exists('space') checks for a function before you call it. meta.load-css('theme') includes another stylesheet's output inside a mixin or a rule, which @use cannot do.
Global functions are deprecated
Older Sass code calls map-get($map, key), percentage(0.5), or darken($color, 10%) without a module. These global functions are deprecated, and they will eventually be removed. Each one has a module equivalent.
| Old global function | Module form |
|---|---|
| `map-get($m, $k)` | `map.get($m, $k)` |
| `map-merge($a, $b)` | `map.merge($a, $b)` |
| `percentage($n)` | `math.percentage($n)` |
| `round($n)` | `math.round($n)` |
| `nth($list, 2)` | `list.nth($list, 2)` |
| `to-upper-case($s)` | `string.to-upper-case($s)` |
Common errors
- "There is no module with the namespace 'math'." You called
math.divin a file that has no@use 'sass:math'. Namespaces are per file. - "@use rules must be written before any other rules." Move
@useto the top of the file, above any selectors or@mixinblocks. - A property is missing from the output. A
map.getreturnednull. Check the key spelling, or use a checking function likespace()above. - A deep merge lost keys. You used
map.mergeon nested maps. Usemap.deep-merge. - Division warnings. Replace
$a / $bwithmath.div($a, $b).
Exercise
Given $sizes: (sm: 4px, md: 8px);, what does map.set($sizes, lg, 16px) do to $sizes itself, and how do you keep the new entry?
Show answer
It does nothing to $sizes. Sass maps are immutable, so map.set returns a new map containing the extra entry. To keep it, assign the result: $sizes: map.set($sizes, lg, 16px);.
Exercise
Write a function column-width($count) that returns the width of one column in a grid of $count equal columns, as a percentage. Then say what column-width(3) returns.
Show answer
Use @use 'sass:math'; at the top, then @function column-width($count) { @return math.percentage(math.div(1, $count)); }. column-width(3) returns 33.3333333333%.
Exercise
Why does map.merge($theme, (colors: (primary: #6699ff))) lose the danger color, and which function avoids that?
Show answer
map.merge only merges the top level, so the nested colors map is replaced by the new one, which contains only primary. map.deep-merge merges nested maps recursively and keeps danger.