Selector Interpolation and Dynamic Selector Construction

Interpolation uses #{...} to insert a Sass expression into a string or selector. It is useful when generating class names from a variable or loop.

Interpolation should be used deliberately. Dynamically generated selectors can make the final CSS harder to inspect, increase output size, and create unexpected naming collisions if naming conventions are not controlled.

Prefer straightforward selectors when the selector is known in advance. Use interpolation when a repeated, data-driven pattern genuinely benefits from it.

Generate Class Names
$component: "alert";

.#{$component} {
  padding: 1rem;

  &--success {
    border-color: green;
  }

  &--error {
    border-color: crimson;
  }
}
💡 The interpolation expression inserts the value of $component into the selector. Sass generates .alert, .alert--success, and .alert--error. Interpolation is particularly useful in loops, token-driven utility generation, and systematic class naming.
Knowledge Check

What is the purpose of `#{...}` in a Sass selector?