Sub topic 6
Building selectors and values with #{}
Interpolation inserts the result of a Sass expression into a place where Sass would otherwise treat your text literally. This chapter assumes you can write variables, nest rules, and use @each as covered in earlier chapters. It also assumes you know which CSS contexts hold selectors, property names, and values.
What interpolation does
The syntax #{expression} tells Sass to evaluate expression, convert the result to text, and paste that text into the surrounding output. The result is always an unquoted string. Sass does not keep it as a number, color, or list.
That last point explains most interpolation bugs, so keep it in mind through the rest of the chapter.
Where you need it
Sass already evaluates variables in ordinary value positions, so padding: $gap needs no help. Interpolation is for the places Sass treats as plain CSS text.
| Context | Needs `#{}`? | Example |
|---|---|---|
| Selector | Yes | `.text-#{$name}` |
| Property name | Yes | `margin-#{$side}` |
| Normal property value | No | `color: $primary` |
| Custom property value | Yes | `--primary: #{$primary}` |
| Media feature value | No | `@media (min-width: $bp)` |
| Media feature name or whole query | Yes | `@media (#{$feature}: 48rem)` |
| Inside a quoted string | Yes | `"Total: #{$n}"` |
Building selectors and property names
The most common use is generating many related rules from a list. This example creates one margin utility per side.
$sides: top, right, bottom, left;
@each $side in $sides {
.m-#{$side} {
margin-#{$side}: 1rem;
}
}Compiled with sass src/styles.scss dist/styles.css, it produces:
.m-top {
margin-top: 1rem;
}
.m-right {
margin-right: 1rem;
}
.m-bottom {
margin-bottom: 1rem;
}
.m-left {
margin-left: 1rem;
}Interpolation also works with the parent selector. A mixin can add a modifier class to whatever rule includes it:
@mixin variant($name) {
&--#{$name} {
@content;
}
}
.btn {
padding: 0.5rem 1rem;
@include variant(primary) {
background: #3366cc;
}
@include variant(danger) {
background: #cc3333;
}
}The output contains .btn, .btn--primary, and .btn--danger as separate rules. Combining & with a suffix is the usual way to build BEM names (Block, Element, Modifier naming).
Strings and quotes
Interpolation removes quotes from the string it inserts. Quotes around the surrounding text stay.
$font: "Inter";
$label: "Total";
.price {
font-family: #{$font}, sans-serif;
&::before {
content: "#{$label}:";
}
}.price {
font-family: Inter, sans-serif;
}
.price::before {
content: "Total:";
}The font name loses its quotes, which is valid CSS for a single-word family. The content value keeps its quotes because the quotes are written outside the braces. For font names with spaces, such as "Open Sans", leave the variable without interpolation so the quotes survive.
Custom properties
Sass does not evaluate the value of a CSS custom property (--name). The browser reads custom properties as raw text, so Sass leaves them alone. Without interpolation, the variable name is copied into the CSS.
$primary: #3366cc;
$gap: 8px;
:root {
--broken: $primary;
--primary: #{$primary};
--gap: #{$gap * 2};
}:root {
--broken: $primary;
--primary: #3366cc;
--gap: 16px;
}Notice that --gap shows math working inside the braces. The expression $gap * 2 is evaluated as a number first, and only the final 16px becomes text. This is the standard way to bridge Sass variables into runtime CSS variables.
Media queries and the slash
Modern Sass accepts variables directly in a media feature value, so @media (min-width: $bp) works. You need interpolation when the feature name or the whole query comes from a variable:
$feature: "min-width";
@media (#{$feature}: 48rem) {
.nav {
display: flex;
}
}Interpolation is also how you write a literal / in a value. In Sass, / is not division (you use math.div), but some CSS properties such as font use the slash as a separator.
$size: 1rem;
$line-height: 1.5;
body {
font: #{$size}/#{$line-height} Georgia, serif;
}body {
font: 1rem/1.5 Georgia, serif;
}The string trap: no math after interpolation
Because the result is an unquoted string, you cannot do arithmetic on it. This is the most common mistake at the intermediate level.
$base: 10;
.ok {
width: $base * 1px;
}
.bad {
width: #{$base}px * 2;
}The .ok rule works: multiplying a unitless number by 1px yields the number 10px. The .bad rule fails to compile because 10px is a string and cannot be multiplied.
Follow these rules to avoid the trap:
- Use plain
$variablein normal value positions. - Add units with multiplication (
$n * 1px) so the value stays a number. - Reserve
#{}for places where Sass would not evaluate the expression, such as selectors, property names, custom properties, and quoted strings.
What interpolation cannot do
Interpolation builds text. It cannot build Sass identifiers. You cannot write $color-#{$name} to look up a variable by a computed name, because variable names are fixed when Sass parses the file.
The standard fix is a map, which you will see in the maps chapter. A computed key replaces the computed variable name:
@use 'sass:map';
$colors: (
primary: #3366cc,
danger: #cc3333
);
$name: danger;
.alert {
color: map.get($colors, $name);
}The same limit applies to @use paths and to mixin or function names. Interpolation will not generate them.
Edge cases
nullbecomes empty.#{null}inserts nothing, so.a#{null}is just.a. This helps with optional suffixes but hides mistakes when a variable is unexpectedly unset.- Lists are joined with their separators.
#{(1px, 2px)}outputs1px, 2px. Check the output if the separator matters to you. - Nested interpolation works.
#{"a#{$b}"}is legal, but it is rarely clearer than building the string once in a variable. - Whitespace inside the braces is ignored.
#{ $name }equals#{$name}. The text around the braces is kept exactly, so.m- #{$side}creates a descendant selector, not.m-top. - Interpolated selectors are not re-parsed everywhere. Sass will re-parse an interpolated selector for nesting and
@extend, so output such as.a, .bworks. Invalid results, such as a name starting with a digit, produce an error or invalid CSS.
Choosing between interpolation and alternatives
Use interpolation when the output text itself must vary: class names, property names, and custom property values. If you only vary a value, plain variables are better. If you are looking up data by name, use a map. If you are repeating a block of declarations, use a mixin. Interpolation is the glue between those tools and the CSS text they generate.
Exercise
This code is meant to generate .gap-1 { gap: 0.5rem; }, .gap-2 { gap: 1rem; } and .gap-3 { gap: 1.5rem; }, but it fails to compile. Why, and how do you fix it?
@for $i from 1 through 3 {
.gap-$i {
gap: #{$i 0.5}rem 1;
}
}
Show answer
There are two errors. First, $i in the selector is not evaluated, so it must be written .gap-#{$i}. Second, #{$i * 0.5}rem * 1 turns the number into a string and then tries to multiply the string. Use a plain number with a unit instead: gap: $i * 0.5rem;. The fixed code is @for $i from 1 through 3 { .gap-#{$i} { gap: $i * 0.5rem; } }.
Exercise
Write SCSS that takes $brand: #3366cc and $radius: 4px and outputs them as the custom properties --brand and --radius on :root. Explain why --brand: $brand; would not work.
Show answer
Use :root { --brand: #{$brand}; --radius: #{$radius}; }. Sass does not evaluate custom property values, so --brand: $brand; is copied into the CSS as the literal text $brand, which the browser cannot use.