Built-in Modules and Standard Library
1. sass:color Module Functions
| Function | Syntax | Description | Example |
|---|---|---|---|
| adjust() | color.adjust($color, $args...) |
Adjusts color properties by amount | adjust(#6b717f, $red: 15) |
| change() | color.change($color, $args...) |
Sets color properties to value | change(#6b717f, $lightness: 50%) |
| scale() | color.scale($color, $args...) |
Scales properties by percentage | scale(#6b717f, $lightness: 30%) |
| mix() | color.mix($c1, $c2, $weight) |
Blends two colors | mix(#036, #d2e1dd, 75%) |
| invert() | color.invert($color, $weight) |
Inverts color (optional partial) | invert(#6b717f, 80%) |
| complement() | color.complement($color) |
Returns complementary color | complement(#6b717f) |
| grayscale() | color.grayscale($color) |
Removes all saturation | grayscale(#6b717f) |
| ie-hex-str() | color.ie-hex-str($color) |
IE-compatible hex with alpha | ie-hex-str(rgba(0,0,0,0.5)) |
| alpha()/opacity() | color.alpha($color) |
Returns alpha channel (0-1) | alpha(rgba(0,0,0,0.8)) → 0.8 |
| red()/green()/blue() | color.red($color) |
Returns RGB channel (0-255) | red(#6b717f) → 107 |
| hue() | color.hue($color) |
Returns hue (0-360deg) | hue(#6b717f) |
| saturation() | color.saturation($color) |
Returns saturation (0-100%) | saturation(#6b717f) |
| lightness() | color.lightness($color) |
Returns lightness (0-100%) | lightness(#6b717f) |
| whiteness()/blackness() | color.whiteness($color) |
Returns HWB components | HWB color model values |
Example: sass:color module usage
@use 'sass:color';
$base-color: #6b717f;
// adjust() - Increase/decrease by amount
.adjust-demo {
// Adjust individual channels
color: color.adjust($base-color, $red: 15);
background: color.adjust($base-color, $lightness: 10%);
border-color: color.adjust($base-color, $alpha: -0.4);
// Multiple adjustments
outline-color: color.adjust($base-color,
$red: 10,
$blue: -20,
$lightness: 5%
);
}
// change() - Set to specific value
.change-demo {
color: color.change($base-color, $lightness: 50%);
background: color.change($base-color, $alpha: 0.5);
border-color: color.change($base-color, $hue: 180deg);
}
// scale() - Scale by percentage of available range
.scale-demo {
// Scale lightness 30% toward white
color: color.scale($base-color, $lightness: 30%);
// Scale saturation 50% toward grayscale
background: color.scale($base-color, $saturation: -50%);
// Multiple scales
border-color: color.scale($base-color,
$lightness: 40%,
$saturation: 20%
);
}
// Comparison: lighten vs adjust vs scale
$color: #6b717f;
.comparison {
// Old way (deprecated)
// color: lighten($color, 20%);
// adjust - adds 20% lightness
color: color.adjust($color, $lightness: 20%);
// scale - scales 20% toward white (more natural)
background: color.scale($color, $lightness: 20%);
}
// Color mixing
.mix-demo {
// 75% of first color, 25% of second
color: color.mix(#036, #d2e1dd, 75%);
// 50-50 mix (default)
background: color.mix(red, blue);
// Create tints and shades
$tint: color.mix(white, $base-color, 20%);
$shade: color.mix(black, $base-color, 20%);
}
// Color information extraction
.info-demo {
// Get channels
$r: color.red($base-color); // 107
$g: color.green($base-color); // 113
$b: color.blue($base-color); // 127
// HSL values
$h: color.hue($base-color); // 225deg
$s: color.saturation($base-color); // 8.547%
$l: color.lightness($base-color); // 45.882%
// Alpha
$a: color.alpha(rgba(0,0,0,0.5)); // 0.5
}
// Practical: Theme generation
$primary: #007bff;
$theme: (
primary: $primary,
primary-light: color.scale($primary, $lightness: 40%),
primary-dark: color.scale($primary, $lightness: -40%),
primary-pale: color.mix(white, $primary, 80%),
primary-muted: color.scale($primary, $saturation: -60%),
complement: color.complement($primary)
);
// Practical: Contrast-based text color
@function text-color($bg) {
@if color.lightness($bg) > 50% {
@return #000;
} @else {
@return #fff;
}
}
.button {
$bg: #3498db;
background: $bg;
color: text-color($bg); // Returns #fff
}
2. sass:list Module Operations
| Function | Syntax | Description | Example |
|---|---|---|---|
| append() | list.append($list, $val, $sep) |
Adds value to end | append((a, b), c) → a, b, c |
| index() | list.index($list, $value) |
Returns position or null | index((a, b, c), b) → 2 |
| is-bracketed() | list.is-bracketed($list) |
Checks for square brackets | is-bracketed([a, b]) → true |
| join() | list.join($l1, $l2, $sep) |
Combines two lists | join((a, b), (c, d)) |
| length() | list.length($list) |
Returns item count | length((a, b, c)) → 3 |
| nth() | list.nth($list, $n) |
Gets value at position | nth((a, b, c), 2) → b |
| separator() | list.separator($list) |
Returns separator type | comma, space, slash, null |
| set-nth() | list.set-nth($list, $n, $val) |
Replaces value at position | set-nth((a, b), 1, z) → z, b |
| slash() | list.slash($elements...) |
Creates slash-separated list | slash(1em, 1.5em, 2em) |
| zip() | list.zip($lists...) |
Combines lists into sub-lists | zip((a, b), (1, 2)) → (a 1), (b 2) |
Example: sass:list module operations
@use 'sass:list';
// Basic list operations
$colors: red, green, blue;
.list-demo {
// Length
$count: list.length($colors); // 3
// Access by index (1-based)
$first: list.nth($colors, 1); // red
$last: list.nth($colors, -1); // blue
// Find index
$pos: list.index($colors, green); // 2
// Append
$extended: list.append($colors, yellow); // red, green, blue, yellow
// Set value at position
$modified: list.set-nth($colors, 2, orange); // red, orange, blue
}
// Joining lists
.join-demo {
$list1: (a, b);
$list2: (c, d);
// Join with comma (default)
$joined: list.join($list1, $list2); // a, b, c, d
// Join with space
$spaced: list.join($list1, $list2, space); // a b c d
// Join with slash
$slashed: list.join($list1, $list2, slash); // a / b / c / d
}
// Slash-separated lists (for font shorthand)
.slash-demo {
// CSS font shorthand: size / line-height
font: 16px list.slash(1.2em) Arial;
// Creates: 16px / 1.2em Arial
}
// Zip lists together
.zip-demo {
$names: (name1, name2, name3);
$values: (10px, 20px, 30px);
$pairs: list.zip($names, $values);
// Result: (name1 10px), (name2 20px), (name3 30px)
@each $pair in $pairs {
$name: list.nth($pair, 1);
$value: list.nth($pair, 2);
.#{$name} {
padding: $value;
}
}
}
// Practical: Utility list functions
@function contains($list, $value) {
@return list.index($list, $value) != null;
}
@function first($list) {
@return list.nth($list, 1);
}
@function last($list) {
@return list.nth($list, -1);
}
@function rest($list) {
$result: ();
@for $i from 2 through list.length($list) {
$result: list.append($result, list.nth($list, $i));
}
@return $result;
}
// Usage
$items: (a, b, c, d);
.utils {
$has-b: contains($items, b); // true
$head: first($items); // a
$tail: last($items); // d
$remaining: rest($items); // b, c, d
}
// Bracket detection
.brackets {
$regular: (a, b, c);
$bracketed: [a, b, c];
$is-bracket: list.is-bracketed($bracketed); // true
$not-bracket: list.is-bracketed($regular); // false
}
// Separator detection
.separators {
$comma-list: (a, b, c);
$space-list: a b c;
$single: (a,);
$sep1: list.separator($comma-list); // comma
$sep2: list.separator($space-list); // space
$sep3: list.separator($single); // comma
}
3. sass:map Module Utilities
| Function | Syntax | Description | Example |
|---|---|---|---|
| get() | map.get($map, $key) |
Returns value or null | get((a: 1), a) → 1 |
| has-key() | map.has-key($map, $key) |
Checks if key exists | has-key((a: 1), a) → true |
| keys() | map.keys($map) |
Returns list of keys | keys((a: 1, b: 2)) → a, b |
| values() | map.values($map) |
Returns list of values | values((a: 1, b: 2)) → 1, 2 |
| merge() | map.merge($map1, $map2) |
Combines maps (shallow) | Second map overwrites first |
| deep-merge() | map.deep-merge($map1, $map2) |
Recursively merges nested | Merges nested maps too |
| remove() | map.remove($map, $keys...) |
Returns map without keys | remove((a: 1, b: 2), a) |
| set() | map.set($map, $key, $val) |
Adds/updates key-value | set((a: 1), b, 2) |
| deep-remove() | map.deep-remove($map, $keys...) |
Removes nested key path | Deep key removal |
Example: sass:map module utilities
@use 'sass:map';
$theme: (
primary: #007bff,
secondary: #6c757d,
success: #28a745
);
// Basic map operations
.map-demo {
// Get value
$color: map.get($theme, primary); // #007bff
// Check key existence
$has: map.has-key($theme, danger); // false
// Get all keys
$all-keys: map.keys($theme); // primary, secondary, success
// Get all values
$all-vals: map.values($theme); // #007bff, #6c757d, #28a745
}
// Merging maps
.merge-demo {
$defaults: (size: 16px, weight: 400);
$custom: (size: 18px, family: Arial);
// Shallow merge (custom overwrites)
$config: map.merge($defaults, $custom);
// Result: (size: 18px, weight: 400, family: Arial)
}
// Deep merge for nested maps
.deep-merge-demo {
$theme1: (
colors: (
primary: blue,
secondary: gray
),
spacing: (
sm: 8px
)
);
$theme2: (
colors: (
primary: red, // Overwrites
accent: green // Adds
),
spacing: (
md: 16px // Adds
)
);
$merged: map.deep-merge($theme1, $theme2);
// Result: (
// colors: (primary: red, secondary: gray, accent: green),
// spacing: (sm: 8px, md: 16px)
// )
}
// Adding/updating values
.set-demo {
$colors: (red: #f00, green: #0f0);
// Add new key
$updated: map.set($colors, blue, #00f);
// (red: #f00, green: #0f0, blue: #00f)
// Update existing
$modified: map.set($colors, red, #ff0000);
// (red: #ff0000, green: #0f0)
// Set multiple (chain calls)
$multi: map.set($colors, blue, #00f);
$multi: map.set($multi, yellow, #ff0);
}
// Removing keys
.remove-demo {
$config: (a: 1, b: 2, c: 3, d: 4);
// Remove single key
$removed: map.remove($config, b);
// (a: 1, c: 3, d: 4)
// Remove multiple keys
$cleaned: map.remove($config, a, c);
// (b: 2, d: 4)
}
// Practical: Safe map access with default
@function map-get-default($map, $key, $default) {
@if map.has-key($map, $key) {
@return map.get($map, $key);
}
@return $default;
}
$settings: (timeout: 5000);
.safe-access {
$timeout: map-get-default($settings, timeout, 3000); // 5000
$retries: map-get-default($settings, retries, 3); // 3 (default)
}
// Practical: Map iteration helpers
@function map-to-list($map) {
$list: ();
@each $key, $value in $map {
$list: list.append($list, ($key, $value));
}
@return $list;
}
@function filter-map($map, $keys) {
$result: ();
@each $key in $keys {
@if map.has-key($map, $key) {
$result: map.set($result, $key, map.get($map, $key));
}
}
@return $result;
}
// Advanced: Nested map access
@function deep-get($map, $keys...) {
@each $key in $keys {
$map: map.get($map, $key);
@if $map == null {
@return null;
}
}
@return $map;
}
$theme-config: (
colors: (
primary: (
base: #007bff,
light: #3395ff,
dark: #0056b3
)
)
);
.deep-access {
$base-color: deep-get($theme-config, colors, primary, base);
// Returns: #007bff
}
4. sass:math Module Calculations
| Function | Syntax | Description | Example |
|---|---|---|---|
| abs() | math.abs($number) |
Absolute value | abs(-15) → 15 |
| ceil() | math.ceil($number) |
Round up | ceil(4.2) → 5 |
| floor() | math.floor($number) |
Round down | floor(4.8) → 4 |
| round() | math.round($number) |
Round to nearest | round(4.5) → 5 |
| max() | math.max($numbers...) |
Largest value | max(1, 5, 3) → 5 |
| min() | math.min($numbers...) |
Smallest value | min(1, 5, 3) → 1 |
| clamp() | math.clamp($min, $val, $max) |
Constrain between min/max | clamp(0, 150, 100) → 100 |
| div() | math.div($num1, $num2) |
Division (replaces /) | div(100px, 2) → 50px |
| percentage() | math.percentage($number) |
Convert to percentage | percentage(0.5) → 50% |
| pow() | math.pow($base, $exponent) |
Exponentiation | pow(2, 3) → 8 |
| sqrt() | math.sqrt($number) |
Square root | sqrt(16) → 4 |
| cos()/sin()/tan() | math.cos($angle) |
Trigonometric functions | cos(0deg) → 1 |
| acos()/asin()/atan()/atan2() | math.acos($number) |
Inverse trig functions | Returns angle |
| log() | math.log($number, $base) |
Logarithm | log(100, 10) → 2 |
| unit() | math.unit($number) |
Returns unit string | unit(10px) → "px" |
| is-unitless() | math.is-unitless($number) |
Checks if no unit | is-unitless(10) → true |
| compatible() | math.compatible($n1, $n2) |
Can units be added? | compatible(1px, 1em) → false |
Example: sass:math module calculations
@use 'sass:math';
// Basic arithmetic
.math-demo {
// Division (NEW way in Dart Sass)
width: math.div(100%, 3); // 33.333%
padding: math.div(24px, 2); // 12px
// Rounding
$value: 4.7;
font-size: math.ceil($value); // 5
line-height: math.floor($value); // 4
margin: math.round($value); // 5
// Min/Max
width: math.max(300px, 50%, 20vw);
padding: math.min(2rem, 5%);
// Clamp (constrain value)
font-size: math.clamp(14px, 2vw, 24px);
}
// Advanced math
.advanced {
// Exponents
$size: math.pow(2, 4); // 16
// Square root
$diagonal: math.sqrt(2) * 100px; // ~141.42px
// Absolute value
margin: math.abs(-20px); // 20px
// Percentage conversion
width: math.percentage(math.div(3, 4)); // 75%
}
// Trigonometry (angles)
.trig-demo {
// Trigonometric functions
$angle: 45deg;
$cos-val: math.cos($angle); // 0.707...
$sin-val: math.sin($angle); // 0.707...
$tan-val: math.tan($angle); // 1
// Inverse trig
$acos-val: math.acos(0.5); // 60deg
$asin-val: math.asin(1); // 90deg
$atan-val: math.atan(1); // 45deg
}
// Logarithms
.log-demo {
// Natural log (base e)
$ln: math.log(math.$e); // 1
// Log base 10
$log10: math.log(100, 10); // 2
// Log base 2
$log2: math.log(8, 2); // 3
}
// Mathematical constants
.constants {
// Euler's number
$e: math.$e; // 2.718281828459045
// Pi
$pi: math.$pi; // 3.141592653589793
// Usage
$circle-area: math.$pi * math.pow(5px, 2);
}
// Unit operations
.units {
$px-value: 16px;
$unitless: 10;
// Check if unitless
$is-plain: math.is-unitless($unitless); // true
$has-unit: math.is-unitless($px-value); // false
// Get unit
$unit-str: math.unit($px-value); // "px"
// Check compatibility
$can-add: math.compatible(1px, 1em); // false
$can-add2: math.compatible(1px, 2px); // true
}
// Practical: Fluid typography
@function fluid-size($min, $max, $min-vw: 320px, $max-vw: 1200px) {
$slope: math.div($max - $min, $max-vw - $min-vw);
$y-intercept: $min - $slope * $min-vw;
@return calc(#{$y-intercept} + #{$slope * 100}vw);
}
.heading {
font-size: fluid-size(16px, 32px);
}
// Practical: Aspect ratio padding
@function aspect-ratio($width, $height) {
@return math.percentage(math.div($height, $width));
}
.video-16-9 {
padding-bottom: aspect-ratio(16, 9); // 56.25%
}
// Practical: Grid column width
@function grid-column-width($columns, $total: 12, $gutter: 30px) {
$column-width: math.div(100% - ($total - 1) * $gutter, $total);
$width: $column-width * $columns + ($columns - 1) * $gutter;
@return math.floor($width * 100) * 0.01%;
}
.col-4 {
width: grid-column-width(4);
}
// Practical: Modular scale
@function modular-scale($level, $base: 16px, $ratio: 1.618) {
@return $base * math.pow($ratio, $level);
}
h1 { font-size: modular-scale(4); } // 68.773px
h2 { font-size: modular-scale(3); } // 42.517px
h3 { font-size: modular-scale(2); } // 26.287px
Note: Use
math.div() instead of / for division in Dart Sass. The
/ operator is deprecated for division.
5. sass:meta Module Reflection Functions
| Function | Syntax | Description | Use Case |
|---|---|---|---|
| type-of() | meta.type-of($value) |
Returns type as string | Type checking, validation |
| inspect() | meta.inspect($value) |
String representation | Debugging, logging |
| variable-exists() | meta.variable-exists($name) |
Check if var defined | Conditional logic |
| global-variable-exists() | meta.global-variable-exists($name) |
Check global var | Scope validation |
| function-exists() | meta.function-exists($name) |
Check if function defined | Feature detection |
| mixin-exists() | meta.mixin-exists($name) |
Check if mixin defined | Conditional includes |
| get-function() | meta.get-function($name) |
Returns function reference | Dynamic function calls |
| call() | meta.call($function, $args...) |
Invoke function dynamically | Callback patterns |
| content-exists() | meta.content-exists() |
Check if @content passed | Conditional @content |
| keywords() | meta.keywords($args) |
Extract keyword arguments | Argument handling |
| module-functions() | meta.module-functions($module) |
List module's functions | Introspection |
| module-variables() | meta.module-variables($module) |
List module's variables | Introspection |
Example: sass:meta reflection and introspection
@use 'sass:meta';
@use 'sass:map';
// Type checking
.type-demo {
$value: 10px;
$type: meta.type-of($value); // "number"
// All types: number, string, color, list, map,
// bool, null, function, arglist
@if meta.type-of($value) == 'number' {
width: $value;
}
}
// Inspect for debugging
@debug meta.inspect((a: 1, b: 2)); // "(a: 1, b: 2)"
@debug meta.inspect(#f00); // "red"
// Variable existence checking
$global-color: red;
@mixin conditional-color {
@if meta.variable-exists(local-color) {
color: $local-color;
} @else if meta.global-variable-exists(global-color) {
color: $global-color;
} @else {
color: black;
}
}
// Function/mixin existence
@mixin apply-if-exists($mixin-name) {
@if meta.mixin-exists($mixin-name) {
@include meta.get-mixin($mixin-name);
} @else {
@warn "Mixin #{$mixin-name} does not exist";
}
}
// Dynamic function calls
@function add($a, $b) {
@return $a + $b;
}
@function multiply($a, $b) {
@return $a * $b;
}
.dynamic-call {
// Get function reference
$fn: meta.get-function('add');
// Call it dynamically
$result: meta.call($fn, 10, 5); // 15
// Or in one step
$result2: meta.call(meta.get-function('multiply'), 3, 4); // 12
}
// Practical: Function dispatcher
@function calculate($operation, $a, $b) {
@if meta.function-exists($operation) {
$fn: meta.get-function($operation);
@return meta.call($fn, $a, $b);
}
@error "Unknown operation: #{$operation}";
}
.calculator {
width: calculate('add', 100px, 50px); // 150px
height: calculate('multiply', 10px, 3); // 30px
}
// Content existence checking
@mixin wrapper {
.wrapper {
padding: 1rem;
@if meta.content-exists() {
@content;
} @else {
// Default content
background: gray;
}
}
}
@include wrapper {
background: blue; // Custom content
}
@include wrapper; // Uses default
// Keywords extraction
@mixin button($args...) {
$config: meta.keywords($args);
background: map.get($config, bg) or blue;
color: map.get($config, color) or white;
padding: map.get($config, padding) or 10px;
}
.btn {
@include button($bg: red, $padding: 15px);
}
// Module introspection
@use 'sass:math';
.introspection {
// List all functions in math module
$math-functions: meta.module-functions('math');
// Returns map: (abs: function, ceil: function, ...)
// List all variables (if any)
$math-vars: meta.module-variables('math');
// Returns map with $e, $pi, etc.
}
// Advanced: Type-safe function
@function safe-divide($a, $b) {
@if meta.type-of($a) != 'number' {
@error "$a must be a number, got #{meta.type-of($a)}";
}
@if meta.type-of($b) != 'number' {
@error "$b must be a number, got #{meta.type-of($b)}";
}
@if $b == 0 {
@error "Division by zero";
}
@return $a / $b;
}
// Practical: Plugin system
$_plugins: ();
@mixin register-plugin($name, $function) {
$_plugins: map.merge($_plugins, ($name: $function)) !global;
}
@function run-plugin($name, $args...) {
@if map.has-key($_plugins, $name) {
$fn: map.get($_plugins, $name);
@return meta.call($fn, $args...);
}
@error "Plugin #{$name} not found";
}
6. sass:selector Module Manipulation
| Function | Syntax | Description | Use Case |
|---|---|---|---|
| append() | selector.append($selectors...) |
Combines selectors | Compound selectors |
| extend() | selector.extend($sel, $ex, $exd) |
Extends selectors | Programmatic @extend |
| nest() | selector.nest($selectors...) |
Nests selectors | Dynamic nesting |
| parse() | selector.parse($selector) |
Converts string to selector | String to selector list |
| replace() | selector.replace($sel, $old, $new) |
Replaces selector part | Selector transformation |
| unify() | selector.unify($sel1, $sel2) |
Combines if possible | Selector intersection |
| is-superselector() | selector.is-superselector($s, $c) |
Checks if s contains c | Specificity checking |
| simple-selectors() | selector.simple-selectors($sel) |
Breaks into components | Selector analysis |
Example: sass:selector manipulation
@use 'sass:selector';
// Parse selector from string
.parse-demo {
$parsed: selector.parse('.foo .bar, .baz');
// Returns: ((.foo .bar), (.baz))
}
// Nest selectors programmatically
.nest-demo {
$parent: '.parent';
$child: '.child';
$nested: selector.nest($parent, $child);
// Returns: .parent .child
$complex: selector.nest('.outer', '.inner', '.deep');
// Returns: .outer .inner .deep
}
// Append selectors (no space)
.append-demo {
$base: '.button';
$modifier: '.--primary';
$combined: selector.append($base, $modifier);
// Returns: .button.--primary
// Multiple appends
$multi: selector.append('.btn', '.is-active', ':hover');
// Returns: .btn.is-active:hover
}
// Replace selector parts
.replace-demo {
$selector: '.old-class .nested';
$updated: selector.replace($selector, '.old-class', '.new-class');
// Returns: .new-class .nested
}
// Unify selectors (intersection)
.unify-demo {
$unified: selector.unify('.button', '.primary');
// Returns: .button.primary
$tags: selector.unify('div', '.class');
// Returns: div.class
// Incompatible returns null
$incomp: selector.unify('div', 'span');
// Returns: null (can't be both)
}
// Check superselector
.superselector-demo {
$is-super: selector.is-superselector('.a .b', '.b');
// true - '.a .b' matches all '.b' would match
$not-super: selector.is-superselector('.b', '.a .b');
// false
}
// Simple selectors breakdown
.simple-demo {
$simple: selector.simple-selectors('.btn.is-active[disabled]');
// Returns: ('.btn', '.is-active', '[disabled]')
}
// Practical: BEM modifier generator
@function bem-modifier($block, $modifiers...) {
$selectors: ();
@each $modifier in $modifiers {
$sel: selector.append($block, '--#{$modifier}');
$selectors: list.append($selectors, $sel, comma);
}
@return $selectors;
}
#{bem-modifier('.button', 'primary', 'large', 'disabled')} {
// Generates: .button--primary, .button--large, .button--disabled
display: inline-block;
}
// Practical: Dynamic theming
@mixin theme-variants($selector, $themes) {
@each $theme, $color in $themes {
$themed-selector: selector.nest('.theme-#{$theme}', $selector);
#{$themed-selector} {
background: $color;
}
}
}
@include theme-variants('.card', (light: #fff, dark: #333, blue: #007bff));
// Generates:
// .theme-light .card { background: #fff; }
// .theme-dark .card { background: #333; }
// .theme-blue .card { background: #007bff; }
7. sass:string Module Processing
| Function | Syntax | Description | Example |
|---|---|---|---|
| quote() | string.quote($string) |
Adds quotes | quote(Arial) → "Arial" |
| unquote() | string.unquote($string) |
Removes quotes | unquote("Arial") → Arial |
| length() | string.length($string) |
Character count | length("hello") → 5 |
| index() | string.index($str, $substr) |
Position of substring | index("hello", "ll") → 3 |
| insert() | string.insert($str, $ins, $idx) |
Inserts at position | insert("abc", "X", 2) → "aXbc" |
| slice() | string.slice($str, $start, $end) |
Extracts substring | slice("hello", 2, 4) → "ell" |
| to-upper-case() | string.to-upper-case($str) |
Converts to uppercase | to-upper-case("hi") → "HI" |
| to-lower-case() | string.to-lower-case($str) |
Converts to lowercase | to-lower-case("HI") → "hi" |
| unique-id() | string.unique-id() |
Generates unique string | unique-id() → "u4b2c3d4" |
Example: sass:string processing
@use 'sass:string';
// Basic string operations
.string-demo {
$text: "Hello World";
// Length
$len: string.length($text); // 11
// Find substring
$pos: string.index($text, "World"); // 7
// Extract
$sub: string.slice($text, 1, 5); // "Hello"
$last: string.slice($text, -5, -1); // "World"
// Insert
$inserted: string.insert($text, " Beautiful", 6);
// "Hello Beautiful World"
// Case conversion
$upper: string.to-upper-case($text); // "HELLO WORLD"
$lower: string.to-lower-case($text); // "hello world"
}
// Quote handling
.quote-demo {
$unquoted: Arial;
$quoted: "Helvetica";
$add-quotes: string.quote($unquoted); // "Arial"
$remove-quotes: string.unquote($quoted); // Helvetica
// Font family with spaces
$font: Open Sans;
font-family: string.quote($font); // "Open Sans"
}
// Unique IDs
.unique-demo {
$id1: string.unique-id(); // "u1a2b3c4"
$id2: string.unique-id(); // "u5d6e7f8" (different)
// Use for animation names
$anim-name: 'slide-' + string.unique-id();
animation-name: string.unquote($anim-name);
}
// Practical: String replacement
@function str-replace($string, $search, $replace: '') {
$index: string.index($string, $search);
@if $index {
$before: string.slice($string, 1, $index - 1);
$after: string.slice($string, $index + string.length($search));
@return $before + $replace + str-replace($after, $search, $replace);
}
@return $string;
}
.replace-demo {
$path: "assets/images/icon.png";
$new-path: str-replace($path, "assets", "public");
// Result: "public/images/icon.png"
}
// Practical: String contains
@function str-contains($string, $substring) {
@return string.index($string, $substring) != null;
}
.contains-demo {
$url: "https://example.com";
$is-https: str-contains($url, "https"); // true
}
// Practical: Camel case to kebab case
@function to-kebab-case($string) {
$result: '';
@for $i from 1 through string.length($string) {
$char: string.slice($string, $i, $i);
$lower: string.to-lower-case($char);
@if $char != $lower and $i > 1 {
$result: $result + '-' + $lower;
} @else {
$result: $result + $lower;
}
}
@return $result;
}
.kebab {
// backgroundColor → background-color
$kebab: to-kebab-case("backgroundColor");
}
// Practical: Truncate with ellipsis
@function truncate-string($string, $max-length) {
@if string.length($string) > $max-length {
@return string.slice($string, 1, $max-length - 3) + '...';
}
@return $string;
}
.truncate {
content: string.unquote('"' + truncate-string("Very long text here", 10) + '"');
// "Very lo..."
}
Built-in Modules Summary
sass:color- Comprehensive color manipulation (adjust, scale, mix)sass:list- List operations (append, join, zip, nth)sass:map- Map utilities (get, set, merge, deep-merge)sass:math- Mathematical calculations (div, pow, trig, constants)sass:meta- Reflection and introspection (type-of, call, inspect)sass:selector- Selector manipulation (nest, append, parse)sass:string- String processing (slice, index, case conversion)- All modules require
@use 'sass:module-name';in modern Sass
Note: Built-in modules are namespaced in Dart Sass. Always use
@use 'sass:module' instead of global functions.