Sub topic 2
Building Selectors and Values with #{}
Assume you know CSS selectors, properties, media queries, and basic command-line use. Sass interpolation, written #{...}, inserts a Sass value into a selector or property value.
Building selectors and values
Interpolation is useful when a selector or value depends on a variable. It commonly appears with maps and loops:
@use "sass:map";
@use "sass:math";
$prefix: "card";
$gap: 24px;
$colors: (
primary: #3366cc,
danger: #cc3333
);
@function rem($px, $base: 16px) {
@return math.div($px, $base) * 1rem;
}
@mixin respond($min-width) {
@media (min-width: $min-width) {
@content;
}
}
.#{$prefix} {
padding: rem($gap);
--card-gap: #{$gap};
@include respond(48rem) {
display: grid;
gap: $gap;
}
}
@each $name, $color in $colors {
.text-#{$name} {
color: $color;
}
}This generates selectors such as .card and .text-primary. The expression #{$gap} places 24px into a custom property value.
A common error is using interpolation when ordinary Sass evaluation is enough. Write padding: $gap * 2 for arithmetic. Use interpolation when constructing text, selectors, or values that need Sass values inserted into them.
Arithmetic with sass:math
Modern Dart Sass provides arithmetic functions through built-in modules. math.div() makes division explicit:
@use "sass:math";
.container {
width: math.div(960px, 12);
font-size: math.div(24px, 16px) * 1rem;
}Explicit units help prevent accidental calculations between incompatible values.
Mixins and functions
A mixin produces reusable declarations. It can accept arguments and receive a caller's declarations through @content. A function returns one value, such as a converted length.
Use a mixin for a group of declarations. Use a function when you need a calculated value inside a declaration.
Maps and design tokens
A map stores related key-value pairs. With @each, it can generate consistent utility classes or component variants. Keep token names stable, and use map.get() when reading a map through the sass:map module.
>``callout note >Interpolation creates text. It does not automatically make arbitrary text a safe or valid CSS selector. Keep interpolated names under your control. >``
Exercise
What selector does .text-#{$name} produce when $name is danger?
Show answer
It produces .text-danger.