Variable interpolation lets you insert variable values inside strings or selectors in Sass. It helps create dynamic styles easily.
0
0
Variable interpolation with #{} in SASS
Introduction
When you want to combine variables with text in CSS property names or values.
When creating dynamic class or ID names using variables.
When you need to build complex selectors that include variable parts.
When you want to generate CSS rules with variable parts inside strings.
When you want to reuse values inside strings without repeating them.
Syntax
SASS
$variable: value; .some-class-#{$variable} { property: value; }
Use #{} to insert a variable inside strings or selectors.
Interpolation works inside selectors, property names, and property values.
Examples
This creates a class named
.button-red and sets its text color to red.SASS
$color: red; .button-#{$color} { color: $color; }
This creates a class
.container-large with a font size of 2rem.SASS
$size: large; .container-#{$size} { font-size: 2rem; }
This sets
margin-left: 10px; inside a class named .margin-left.SASS
$side: left; .margin-#{$side} { margin-#{$side}: 10px; }
Sample Program
This Sass code creates two classes: .button-dark and .alert-dark. Both use the $theme variable inside their names. The .button-dark has a blue background and white text. The .alert-dark has a border and lighter text color based on the main color.
SASS
@use 'sass:color'; $theme: dark; $main-color: #3498db; .button-#{$theme} { background-color: $main-color; color: white; padding: 1rem 2rem; border-radius: 0.5rem; } .alert-#{$theme} { border: 2px solid $main-color; color: color.scale($main-color, $lightness: 50%); padding: 1rem; margin-top: 1rem; }
OutputSuccess
Important Notes
Interpolation only works inside strings or selectors, not directly in variable declarations.
You can interpolate any Sass expression inside #{}, not just variables.
Summary
Use #{} to insert variables inside strings or selectors.
It helps create dynamic class names, property names, and values.
Interpolation makes your styles more flexible and reusable.