Interpolation #{}
Inject variables into selectors, property names, and strings.
Syntax
#{$variable} .icon-#{$name} { }Interpolation #{ } inserts the value of an expression into places where Sass would not otherwise evaluate it — selectors, property names, and unquoted strings.
Where you need it
- Building a selector or class name from a variable.
- Constructing a property name dynamically.
- Placing a value inside a string or a
url().
You do not need interpolation for a normal property value — color: $brand already works.
Example
$side: 'left';
$name: 'warning';
.alert-#{$name} {
border-#{$side}: 4px solid #CC6699;
background: url('icons/#{$name}.svg');
}
/* Compiles to:
.alert-warning {
border-left: 4px solid #CC6699;
background: url('icons/warning.svg');
}
*/When to use it
- A loop uses #{$name} interpolation to inject a variable's value directly into a selector string, generating .icon-arrow, .icon-close etc.
- A developer builds a dynamic CSS custom property name by interpolating a token key into the string --color-#{$token}.
- A mixin constructs a url() path by interpolating a base-path variable and a filename argument into a single string value.
More examples
Interpolation in selectors
Injects the loop variable into the selector string with #{} to generate .btn-primary, .btn-secondary, and .btn-danger.
$variants: primary, secondary, danger;
@each $v in $variants {
.btn-#{$v} {
@extend %btn-base;
}
}Interpolation in property values
Combines two variables inside a url() string using interpolation, building a dynamic asset path for each icon.
$icon-path: '/assets/icons';
$icons: arrow, close, menu;
@each $name in $icons {
.icon-#{$name} {
background-image: url('#{$icon-path}/#{$name}.svg');
}
}Interpolation for CSS custom properties
Generates CSS custom property declarations by interpolating both the map key into the property name and the value into the property value.
@use 'sass:map';
$colors: (primary: #2563eb, success: #16a34a, danger: #dc2626);
:root {
@each $name, $value in $colors {
--color-#{$name}: #{$value};
}
}
Discussion