Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Strings, escaping and interpolation

Sometimes a value has to go into the CSS as it is, without Less parsing or calculating it. That is what escaping is for — the ~"..." notation. And to insert a variable into a selector, a property name or a string you use interpolation, @{name}.

Escaping with ~"..."

Less tries to understand every value. If a value contains something Less does not know, compilation fails. A string with a tilde is output without quotes and without processing:

// styles/main.less
@phone: ~"(max-width: 599px)";
 
.menu {
  @media @phone {
    display: none;
  }
}
@media (max-width: 599px) {
  .menu {
    display: none;
  }
}

The media query condition is kept in a variable and inserted as a whole. The tilde removed the quotes; otherwise the CSS would contain @media "(max-width: 599px)".

Interpolation in selectors and properties

To insert a variable into a class name or a property name, wrap its name in braces: @{name}.

// styles/components/buttons.less
@prefix: app;
@side: left;
 
.@{prefix}-btn {
  margin-@{side}: 8px;
}
.app-btn {
  margin-left: 8px;
}

This is how libraries let you change the prefix of all classes with one variable. In Sass the same thing is written as #{$prefix}.

Interpolation in strings

Inside a quoted string the same notation works — handy for file paths:

// styles/main.less
@images: "/assets/images";
 
.hero {
  background-image: url("@{images}/hero.jpg");
}
.hero {
  background-image: url("/assets/images/hero.jpg");
}

String functions

FunctionWhat it doesExampleResult
e()The same as ~"..."e("a b")a b
%()Puts values in place of %s and %d%("%d of %d", 2, 5)"2 of 5"
replace()Replaces part of a stringreplace("one two", "two", "three")"one three"
escape()Encodes characters for a URLescape("a=1")a%3D1

An example with %() — counter text in a pseudo-element:

// styles/components/cards.less
@total: 5;
 
.card::after {
  content: %("1 / %d", @total);
}
.card::after {
  content: "1 / 5";
}
<style>
  .card::after {
    content: "1 / 5";
  }
</style>
 
<div class="card">The first card</div>

After the card text the pseudo-element shows 1 / 5.

Common mistake

Without the tilde a string variable goes into the CSS together with its quotes:

// styles/main.less
@phone: "(max-width: 599px)";
 
@media @phone {
  .menu {
    display: none;
  }
}
@media "(max-width: 599px)" {
  .menu {
    display: none;
  }
}

The browser does not understand a condition in quotes, and the rule does not work. Write values that must reach the CSS as code, not as text, with ~"...".

Thanks for reading!

Donate to the site — we work hard for you.