liveBook · Manning

Interpolation

As explained in Tiny CSS Projects

Sass interpolation evaluates an expression and inserts its result into generated CSS text, such as selectors, property names, or values.

Sass interpolation evaluates an expression and inserts its result into generated CSS text. Write the expression as #{$variable}; Sass replaces the hash and braces with the value. section 12.3.2

Constructing a property name

A variable can supply part of a declaration: `margin-#{$side}: 0;`. When `$side` is `left`, Sass compiles this to `margin-left: 0;`. Interpolation also creates selectors and generated content, as in `.#{$type}` and `content: "#{$type}: ";`. section 12.3.2 section 12.5

Listing 12.22 Adding to the loop (SCSS)
.callout {
  border: solid 1px;
  border-radius: 4px;
  padding: .5rem 1rem;
}
 
$callouts: (success: $success, warning: $warning, error: $error);
@each $type, $color in $callouts {
@debug $type, $color;
  .#{$type} {                       #1
    @extend .callout;
    border-color: $color;
    &::before {
      content: "#{$type}: ";        #2
      text-transform: capitalize;
    }
  }
}

Inspect the complete @each loop to see interpolation create a class selector and readable pseudo-element label for each callout type. section 12.5

Interpolation is especially useful when looping through Sass maps: each key can become a class name and its label can become visible text. This supports multiple generated rules while keeping the source concise. section 12.5

How Tiny CSS Projects covers it

How deep it goes
Defines the hash-and-braces syntax and demonstrates compilation, but does not descend into Sass implementation internals.
Examples
Shows a dynamic margin declaration and generated success, warning, and error callout classes and labels.
What it assumes
Assumes Sass variables or expressions and teaches the interpolation syntax needed to embed their results in CSS.
What you can do after
Apply it via Sass to construct CSS names and text from variables while generating repeated rules from maps.
How it connects
Connects Sass variables and expressions with @each loops, Sass maps, selectors, and pseudo-elements.

Also explained in

Compare how 4 books explain interpolation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny CSS Projects. The section links point to the parts of the book it draws on.