CSS PREprocessors

Variable Interpolation

by

You can interpolate a variable anywhere - in the property, value, and even the selector.

@var: color;

.class-@{var} {
  @{var}: #7b3d66;
  background-@{var}: #7b3d66;
  content: @var;
}
$var: color;

.class-#{$var} {
  #{$var}: #7b3d66;
  background-#{$var}: #7b3d66;
  content: $var;
}
$var: color

.class-#{$var}
  #{$var}: #7b3d66
  background-#{$var}: #7b3d66
  content: $var
$var = color

.class-{$var}
  {$var}: #7b3d66
  background-{$var}: #7b3d66
  content: $var
$var: color;

.class-$var {
  $(var): #7b3d66;
  background-$(var): #7b3d66;
  content: $var;
}
.class-color {
  color: #7b3d66;
  background-color: #7b3d66;
  content: color;
}

Interpolation in calc()

Some preprocessors require more special treatment when using variables inside calc():

@var: 5px;

div {
  height: ~"calc(7em + @{var})";
}
$var: 5px;

div {
  height: calc(7em + #{$var});
}
$var: 5px

div
  height: calc(7em + #{$var})
$var = 5px

div
  height: "calc(7em + %s)" % $var
$var: 5px;

div {
  height: calc(7em + $var);
}
div {
  height: calc(7em + 5px);
}

Selectors interpolation

If you have a often-occuring selector pattern you can put it in a variable:

@headings: h1, .h1, h2, .h2, h3, .h3;

@{headings} {
  font-family: "Great Custom Font", sans-serif;
}
$headings: "h1, .h1, h2, .h2, h3, .h3";

#{$headings} {
  font-family: "Great Custom Font", sans-serif;
}
$headings: "h1, .h1, h2, .h2, h3, .h3"

#{$headings}
  font-family: "Great Custom Font", sans-serif
$headings = h1, .h1, h2, .h2, h3, .h3

{$headings}
  font-family: "Great Custom Font", sans-serif
$headings: h1, .h1, h2, .h2, h3, .h3;

$headings {
  font-family: "Great Custom Font", sans-serif;
}
h1, .h1, h2, .h2, h3, .h3 {
  font-family: "Great Custom Font", sans-serif;
}

Less needs escaping when you have both a dot (.) and a hyphen (-) in a variable because of reasons.

Nested selectors interpolation

If you often find yourself extending selectors with the same pseudo selectors and/or modifier classes, then you can again use a variable like in the example above, when nesting though this won't work in Less.

$active: "&.is-active, &:hover";

.selector {
  foo: bar;
  #{$active} {
    baz: qux;
  }
}
$active: "&.is-active, &:hover"

.selector
  foo: bar
  #{$active}
    baz: qux
$active = "&.is-active, &:hover"

.selector
  foo: bar
  {$active}
    baz: qux
.selector {
  foo: bar;
}
.selector.is-active,
.selector:hover {
  baz: qux;
}

An alternative way of achieving this is using the @content directive which supports Less.

Interactive

Leave a comment below or suggest improvements on GitHub.