The sass:string and sass:list modules
Besides numbers and colours, Sass works with strings — text like "icons/home.svg" — and lists — several values in a row, like 12px 16px 20px. The sass:string and sass:list modules give functions for both. They are most useful inside mixins, functions and loops.
Strings
A string can be quoted ("Inter") or unquoted (bold). + joins strings, and the sass:string module does the rest:
// styles/main.scss
@use "sass:string";
$icon: "cart";
.icon-cart {
background-image: url("/icons/" + $icon + ".svg");
}
.label {
content: string.to-upper-case("new");
font-family: string.unquote("'Inter', sans-serif");
}.icon-cart {
background-image: url("/icons/cart.svg");
}
.label {
content: "NEW";
font-family: 'Inter', sans-serif;
}string.unquote() removed the outer quotes, so the inner single quotes went into the CSS as they are.
| Function | Result |
|---|---|
string.length("hello") | 5 |
string.index("btn-primary", "-") | 4 |
string.slice("btn-primary", 5) | "primary" |
string.to-upper-case("new") | "NEW" |
string.quote(bold) | "bold" |
Positions in Sass start at 1, not 0 as in JavaScript.
Lists
A list is values separated by spaces or commas. You already wrote lists: 8px 16px in padding and system-ui, sans-serif in font-family. A list can also be stored in a variable — for example, the site's font sizes:
// styles/abstracts/_variables.scss
$font-sizes: 14px 16px 20px 28px;list.nth() takes an item by its number:
// styles/main.scss
@use "sass:list";
@use "abstracts/variables";
h1 {
font-size: list.nth(variables.$font-sizes, 4);
}
small {
font-size: list.nth(variables.$font-sizes, 1);
}h1 {
font-size: 28px;
}
small {
font-size: 14px;
}<style>
h1 {
font-size: 28px;
}
small {
font-size: 14px;
}
</style>
<h1>Heading</h1>
<small>Small print</small>Changing lists
Lists in Sass never change in place: functions return a new list, which you save to a variable:
// styles/main.scss
@use "sass:list";
$fonts: Inter, Arial;
$fonts: list.append($fonts, sans-serif);
$heading-fonts: list.join(Georgia, $fonts);
body {
font-family: $fonts;
}
h1 {
font-family: $heading-fonts;
}body {
font-family: Inter, Arial, sans-serif;
}
h1 {
font-family: Georgia, Inter, Arial, sans-serif;
}| Function | What it does |
|---|---|
list.length($list) | Number of items |
list.nth($list, $n) | Item number $n; -1 is the last one |
list.append($list, $value) | New list with one more item |
list.join($list1, $list2) | Two lists joined into one |
list.index($list, $value) | Position of the value or null |
Lists show their full power together with the @each loop, which goes through the items one by one.
Common mistake
list.nth() with a number past the end of the list stops compiling with the error $n: Invalid index 5 for a list with 4 elements. Count from 1, and to take the last item without counting, use -1: list.nth($font-sizes, -1) gives 28px.