Skip to content

Less Language Escaping

SomMeri edited this page Dec 12, 2012 · 28 revisions

Some browsers accept additional proprietary non-standard non-css syntax on top of the usual css. Less is build on top of standard css and therefore may not recognize it. Escaping allows you to use any arbitrary string inside a property value or to as a selector. You can use it to add browser specific features into less. As an additional bonus, you can use it if you need to dynamically build selectors. Dynamic selector building is somewhat limited, but powerful enough to be useful occasionally.

First sub-chapter describes escaping inside property values and second sub-chapter is about selectors escaping. The last one lists all kinds of things that are tempting, but NOT supported.

Property Values

Use either ~"whatever" or ~'whatever' syntax to escape property values. Anything between quotes is placed into final css as is with almost no changes. The "as is" rule has one exception: string interpolation works with the usual @{variableName} syntax.

Sample input:

@variable: "dynamic";
h1 {
  margin: 1 ~"2 2" 3;
  padding: ~'ms:special.syntax()';
  text: ~'@{variable}';
}

compiles into:

h1 {
  margin: 1 2 2 3;
  padding: ms:special.syntax();
  text: dynamic;
}

Note: you can use escaping to put value inside a variable. @escapedVariable: ~"whatever"; is allowed, but has no apparent advantage.

Selectors

TODO

What Is Not Supported

This part lists all kinds of things that NOT supported. Non of following snippets work.

Escaping does NOT allow operations:

.operation {
  margin: ~"2" + 2; // syntax error
}

Only property value can be escaped, nothing else:

#propertyName {
  ~"margin: 2 2 2 2"; // syntax error
  ~"margin": 2; // syntax error
}

Whole selector must be escaped:

(~"h1") h2 { // syntax error
  margin: 2;
}

You can NOT escape mixins names:

(~".mixin")() { // syntax error
  margin: 2;
}

Escaped rulesets can NOT be used as mixins:

(~".mixin") {
  margin: 2;
}
#nope {
  .mixin(); // syntax error
}