Skip to content

Less Language Escaping

SomMeri edited this page Mar 5, 2013 · 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. You may also need to put an otherwise non-parseable value inside a variable and use it to dynamically build selector or other css part during compilation time.

Escaping allows you to use any arbitrary string as property or variable value. It can be used also to dynamically build selectors, but that feature is deprecated and replaced by different more powerful option.

Syntax

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

Used as Property Value

Sample input:

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

compiles into:

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

Used as Variable Value

You can use escaping to put value inside a variable e.g: @escapedVariable: ~".whatever";.

Used to Dynamically Build Selectors

WARNING: selectors escaping has been added into less.js-1.3.0 and deprecated soon after https://github.com/cloudhead/less.js/issues/36. The alternative syntax is described on selectors interpolation wiki page. This chapter describes the old syntax which is currently implemented in less4j, but produces a warning.

Use either (~"whatever") or (~'whatever') syntax to escape selectors. Selector escaping has to be used for the whole selector, you can not escape only part of it.

Ruleset with multiple selectors can use both escaped and non-escaped selectors.

Sample input:

// escaped selector
(~"escaped-selector") {
  margin: 2 2 2 2;
}

// interpolation inside selector
@variable: "variable value";
(~'@{variable}') {
  padding: 2 2 2 2;
}

// multiple selectors
(~".escaped"), .normal, (~".another-escaped") {
  padding: 2 2 2 2;
}

compiles into:

escaped-selector {
  margin: 2 2 2 2;
}
variable value {
  padding: 2 2 2 2;
}
.escaped,
.normal,
.another-escaped {
  padding: 2 2 2 2;
}

What Is Not Supported

This part lists all kinds of things that are NOT supported. None 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
}