Skip to content

Less language Nesting

SomMeri edited this page Nov 10, 2012 · 15 revisions

A ruleset can be nested into another ruleset. Outer ruleset is then compiled as usually, nested rulesets make no difference to it. However, selectors of the nested ruleset are combined with outer selectors. This helps to avoid repetition whenever style sheet contains multiple rulesets with similar selectors. Common part is placed into the outer ruleset while each nested ruleset can add its own parts.

Nested ruleset can use all variables and mixins defined in the outer one, but it will not contain outer selector css properties.

Default Combination

Unless specified otherwise, all nested selectors are considered to be descendants of all outer selectors:

h1, h2 {
  padding: 2 2 2 2;
  :nested, p {
    margin: 3 3 3 3;
  }
}

Output:

h1, h2 {
  padding: 2 2 2 2;
}
h1 :nested, h2 :nested, h1 p, h2 p {
  margin: 3 3 3 3;
}

Nested ruleset can use all variables and mixins defined inside the outer one:

@scope: 1;
h1, h2 {
  scope: @scope;
  :nested, p {
    scope: @scope;
  }
  @scope: 2;
}

Output:

h1, h2 {
  padding: 2;
}
h1 :nested, h2 :nested, h1 p, h2 p {
  margin: 2;
}

Joining Combiner

Prefix nested selector by and css combiner to override default "descendant" behavior:

h1, h2 {
  padding: 2 2 2 2;
  + :nested, >p {
    margin: 3 3 3 3;
  }
}

Output:

h1, h2 {
  padding: 2 2 2 2;
}
h1 + :nested, h2 + :nested, h1 > p, h2 > p {
  margin: 3 3 3 3;
}

Appender