On this page
Less
Overview
An in-depth guide to features of the LESS language. See the Overview for a quick summary of Less.
For an in-depth guide to installing and setting up a Less environment, as well as documentation on developing for Less, see: Using Less.js.
Variables
Control commonly used values in a single location.
Overview
It's not uncommon to see the same value repeated dozens if not hundreds of times across your stylesheets:
a,
.link {
color: #428bca;
}
.widget {
color: #fff;
background: #428bca;
}
Variables make your code easier to maintain by giving you a way to control those values from a single location:
// Variables
@link-color: #428bca; // sea blue
@link-color-hover: darken(@link-color, 10%);
// Usage
a,
.link {
color: @link-color;
}
a:hover {
color: @link-color-hover;
}
.widget {
color: #fff;
background: @link-color;
}
Variable Interpolation
The examples above focused on using variables to control values in CSS rules, but they can also be used in other places as well, such as selector names, property names, URLs and @import statements.
Selectors
v1.4.0
// Variables
@my-selector: banner;
// Usage
.@{my-selector} {
font-weight: bold;
line-height: 40px;
margin: 0 auto;
}
Compiles to:
.banner {
font-weight: bold;
line-height: 40px;
margin: 0 auto;
}
URLs
// Variables
@images: "../img";
// Usage
body {
color: #444;
background: url("@{images}/white-sand.png");
}
Import Statements
v1.4.0
Syntax: @import "@{themes}/tidal-wave.less";
Note that before v2.0.0, only variables which have been declared in the root or current scope were considered and that only the current file and calling files were considered when looking for a variable.
Example:
// Variables
@themes: "../../src/themes";
// Usage
@import "@{themes}/tidal-wave.less";
Properties
v1.6.0
@property: color;
.widget {
@{property}: #0ee;
background-@{property}: #999;
}
Compiles to:
.widget {
color: #0ee;
background-color: #999;
}
Variable Variables
In Less, you can define a variable's name using another variable.
@primary: green;
@secondary: blue;
.section {
@color: primary;
.element {
color: @@color;
}
}
Which compiles to:
.section .element {
color: green;
}
Lazy Evaluation
Variables do not have to be declared before being used.
Valid Less snippet:
.lazy-eval {
width: @var;
}
@var: @a;
@a: 9%;
this is valid Less too:
.lazy-eval {
width: @var;
@a: 9%;
}
@var: @a;
@a: 100%;
both compile into:
.lazy-eval {
width: 9%;
}
When defining a variable twice, the last definition of the variable is used, searching from the current scope upwards. This is similar to css itself where the last property inside a definition is used to determine the value.
For instance:
@var: 0;
.class {
@var: 1;
.brass {
@var: 2;
three: @var;
@var: 3;
}
one: @var;
}
Compiles to:
.class {
one: 1;
}
.class .brass {
three: 3;
}
Essentially, each scope has a "final" value, similar to properties in the browser, like this example using custom properties:
.header {
--color: white;
color: var(--color); // the color is black
--color: black;
}
This means that, unlike other CSS pre-processing languages, Less variables behave very much like CSS's.
Properties as Variables (NEW!)
v3.0.0
You can easily treat properties like variables using the $prop syntax. Sometimes this can make your code a little lighter.
.widget {
color: #efefef;
background-color: $color;
}
Compiles to:
.widget {
color: #efefef;
background-color: #efefef;
}
Note that, like variables, Less will choose the last property within the current/parent scope as being the "final" value.
.block {
color: red;
.inner {
background-color: $color;
}
color: blue;
}
Compiles to:
.block {
color: red;
color: blue;
}
.block .inner {
background-color: blue;
}
Default Variables
We sometimes get requests for default variables - an ability to set a variable only if it is not already set. This feature is not required because you can easily override a variable by putting the definition afterwards.
For instance:
// library
@base-color: green;
@dark-color: darken(@base-color, 10%);
// use of library
@import "library.less";
@base-color: red;
This works fine because of Lazy Loading - @base-color is overridden and @dark-color is a dark red.
Parent Selectors
Referencing parent selectors with &
The & operator represents the parent selectors of a nested rule and is most commonly used when applying a modifying class or pseudo-class to an existing selector:
a {
color: blue;
&:hover {
color: green;
}
}
results in:
a {
color: blue;
}
a:hover {
color: green;
}
Notice that without the &, the above example would result in a :hover rule (a descendant selector that matches hovered elements inside of <a> tags) and this is not what we typically would want with the nested :hover.
The "parent selectors" operator has a variety of uses. Basically any time you need the selectors of the nested rules to be combined in other ways than the default. For example another typical use of the & is to produce repetitive class names:
.button {
&-ok {
background-image: url("ok.png");
}
&-cancel {
background-image: url("cancel.png");
}
&-custom {
background-image: url("custom.png");
}
}
output:
.button-ok {
background-image: url("ok.png");
}
.button-cancel {
background-image: url("cancel.png");
}
.button-custom {
background-image: url("custom.png");
}
Multiple &
& may appear more than once within a selector. This makes it possible to repeatedly refer to a parent selector without repeating its name.
.link {
& + & {
color: red;
}
& & {
color: green;
}
&& {
color: blue;
}
&, &ish {
color: cyan;
}
}
will output:
.link + .link {
color: red;
}
.link .link {
color: green;
}
.link.link {
color: blue;
}
.link, .linkish {
color: cyan;
}
Note that & represents all parent selectors (not just the nearest ancestor) so the following example:
.grand {
.parent {
& > & {
color: red;
}
& & {
color: green;
}
&& {
color: blue;
}
&, &ish {
color: cyan;
}
}
}
results in:
.grand .parent > .grand .parent {
color: red;
}
.grand .parent .grand .parent {
color: green;
}
.grand .parent.grand .parent {
color: blue;
}
.grand .parent,
.grand .parentish {
color: cyan;
}
Changing Selector Order
It can be useful to prepend a selector to the inherited (parent) selectors. This can be done by putting the & after current selector. For example, when using Modernizr, you might want to specify different rules based on supported features:
.header {
.menu {
border-radius: 5px;
.no-borderradius & {
background-image: url('images/button-background.png');
}
}
}
The selector .no-borderradius & will prepend .no-borderradius to its parent .header .menu to form the.no-borderradius .header .menu on output:
.header .menu {
border-radius: 5px;
}
.no-borderradius .header .menu {
background-image: url('images/button-background.png');
}
Combinatorial Explosion
& can also be used to generate every possible permutation of selectors in a comma separated list:
p, a, ul, li {
border-top: 2px dotted #366;
& + & {
border-top: 0;
}
}
This expands to all possible (16) combinations of the specified elements:
p,
a,
ul,
li {
border-top: 2px dotted #366;
}
p + p,
p + a,
p + ul,
p + li,
a + p,
a + a,
a + ul,
a + li,
ul + p,
ul + a,
ul + ul,
ul + li,
li + p,
li + a,
li + ul,
li + li {
border-top: 0;
}
Extend
Extend is a Less pseudo-class which merges the selector it is put on with ones that match what it references.
Released v1.4.0
nav ul {
&:extend(.inline);
background: blue;
}
In the rule set above, the :extend selector will apply the "extending selector" (nav ul) onto the .inline class wherever the .inline class appears. The declaration block will be kept as-is, but without any reference to the extend (because extend isn't css).
So the following:
nav ul {
&:extend(.inline);
background: blue;
}
.inline {
color: red;
}
Outputs
nav ul {
background: blue;
}
.inline,
nav ul {
color: red;
}
Notice how the nav ul:extend(.inline) selector gets output as nav ul - the extend gets removed before output and the selector block left as-is. If no properties are put in that block then it gets removed from the output (but the extend still may affect other selectors).
Extend Syntax
The extend is either attached to a selector or placed into a ruleset. It looks like a pseudo-class with selector parameter optionally followed by the keyword all:
Example:
.a:extend(.b) {}
// the above block does the same thing as the below block
.a {
&:extend(.b);
}
.c:extend(.d all) {
// extends all instances of ".d" e.g. ".x.d" or ".d.x"
}
.c:extend(.d) {
// extends only instances where the selector will be output as just ".d"
}
It can contain one or more classes to extend, separated by commas.
Example:
.e:extend(.f) {}
.e:extend(.g) {}
// the above and the below do the same thing
.e:extend(.f, .g) {}
Extend Attached to Selector
Extend attached to a selector looks like an ordinary pseudo-class with selector as a parameter. A selector can contain multiple extend clauses, but all extends must be at the end of the selector.
- Extend after the selector:
pre:hover:extend(div pre). - Space between selector and extend is allowed:
pre:hover :extend(div pre). - Multiple extends are allowed:
pre:hover:extend(div pre):extend(.bucket tr)- Note this is the same aspre:hover:extend(div pre, .bucket tr) - This is NOT allowed:
pre:hover:extend(div pre).nth-child(odd). Extend must be last.
If a ruleset contains multiple selectors, any of them can have the extend keyword. Multiple selectors with extend in one ruleset:
.big-division,
.big-bag:extend(.bag),
.big-bucket:extend(.bucket) {
// body
}
Extend Inside Ruleset
Extend can be placed into a ruleset's body using &:extend(selector) syntax. Placing extend into a body is a shortcut for placing it into every single selector of that ruleset.
Extend inside a body:
pre:hover,
.some-class {
&:extend(div pre);
}
is exactly the same as adding an extend after each selector:
pre:hover:extend(div pre),
.some-class:extend(div pre) {}
Extending Nested Selectors
Extend is able to match nested selectors. Following less:
Example:
.bucket {
tr { // nested ruleset with target selector
color: blue;
}
}
.some-class:extend(.bucket tr) {} // nested ruleset is recognized
Outputs
.bucket tr,
.some-class {
color: blue;
}
Essentially the extend looks at the compiled css, not the original less.
Example:
.bucket {
tr & { // nested ruleset with target selector
color: blue;
}
}
.some-class:extend(tr .bucket) {} // nested ruleset is recognized
Outputs
tr .bucket,
.some-class {
color: blue;
}
Exact Matching with Extend
Extend by default looks for exact match between selectors. It does matter whether selector uses leading star or not. It does not matter that two nth-expressions have the same meaning, they need to have to same form in order to be matched. The only exception are quotes in attribute selector, less knows they have the same meaning and matches them.
Example:
.a.class,
.class.a,
.class > .a {
color: blue;
}
.test:extend(.class) {} // this will NOT match the any selectors above
Leading star does matter. Selectors *.class and .class are equivalent, but extend will not match them:
*.class {
color: blue;
}
.noStar:extend(.class) {} // this will NOT match the *.class selector
Outputs
*.class {
color: blue;
}
Order of pseudo-classes does matter. Selectors link:hover:visited and link:visited:hover match the same set of elements, but extend treats them as different:
link:hover:visited {
color: blue;
}
.selector:extend(link:visited:hover) {}
Outputs
link:hover:visited {
color: blue;
}
nth Expression
Nth expression form does matter. Nth-expressions 1n+3 and n+3 are equivalent, but extend will not match them:
:nth-child(1n+3) {
color: blue;
}
.child:extend(:nth-child(n+3)) {}
Outputs
:nth-child(1n+3) {
color: blue;
}
Quote type in attribute selector does not matter. All of the following are equivalent.
[title=identifier] {
color: blue;
}
[title='identifier'] {
color: blue;
}
[title="identifier"] {
color: blue;
}
.noQuote:extend([title=identifier]) {}
.singleQuote:extend([title='identifier']) {}
.doubleQuote:extend([title="identifier"]) {}
Outputs
[title=identifier],
.noQuote,
.singleQuote,
.doubleQuote {
color: blue;
}
[title='identifier'],
.noQuote,
.singleQuote,
.doubleQuote {
color: blue;
}
[title="identifier"],
.noQuote,
.singleQuote,
.doubleQuote {
color: blue;
}
Extend "all"
When you specify the all keyword last in an extend argument it tells Less to match that selector as part of another selector. The selector will be copied and the matched part of the selector only will then be replaced with the extend, making a new selector.
Example:
.a.b.test,
.test.c {
color: orange;
}
.test {
&:hover {
color: green;
}
}
.replacement:extend(.test all) {}
Outputs
.a.b.test,
.test.c,
.a.b.replacement,
.replacement.c {
color: orange;
}
.test:hover,
.replacement:hover {
color: green;
}
You can think of this mode of operation as essentially doing a non-destructive search and replace.
Selector Interpolation with Extend
Extend is not able to match selectors with variables. If selector contains variable, extend will ignore it.
However, extend can be attached to interpolated selector.
Selector with variable will not be matched:
@variable: .bucket;
@{variable} { // interpolated selector
color: blue;
}
.some-class:extend(.bucket) {} // does nothing, no match is found
and extend with variable in target selector matches nothing:
.bucket {
color: blue;
}
.some-class:extend(@{variable}) {} // interpolated selector matches nothing
@variable: .bucket;
Both of the above examples compile into:
.bucket {
color: blue;
}
However, :extend attached to an interpolated selector works:
.bucket {
color: blue;
}
@{variable}:extend(.bucket) {}
@variable: .selector;
compiles to:
.bucket, .selector {
color: blue;
}
Scoping / Extend Inside @media
Currently, an :extend inside a @media declaration will only match selectors inside the same media declaration:
@media print {
.screenClass:extend(.selector) {} // extend inside media
.selector { // this will be matched - it is in the same media
color: black;
}
}
.selector { // ruleset on top of style sheet - extend ignores it
color: red;
}
@media screen {
.selector { // ruleset inside another media - extend ignores it
color: blue;
}
}
compiles into:
@media print {
.selector,
.screenClass { /* ruleset inside the same media was extended */
color: black;
}
}
.selector { /* ruleset on top of style sheet was ignored */
color: red;
}
@media screen {
.selector { /* ruleset inside another media was ignored */
color: blue;
}
}
Note: extending does not match selectors inside a nested @media declaration:
@media screen {
.screenClass:extend(.selector) {} // extend inside media
@media (min-width: 1023px) {
.selector { // ruleset inside nested media - extend ignores it
color: blue;
}
}
}
This compiles into:
@media screen and (min-width: 1023px) {
.selector { /* ruleset inside another nested media was ignored */
color: blue;
}
}
Top level extend matches everything including selectors inside nested media:
@media screen {
.selector { /* ruleset inside nested media - top level extend works */
color: blue;
}
@media (min-width: 1023px) {
.selector { /* ruleset inside nested media - top level extend works */
color: blue;
}
}
}
.topLevel:extend(.selector) {} /* top level extend matches everything */
compiles into:
@media screen {
.selector,
.topLevel { /* ruleset inside media was extended */
color: blue;
}
}
@media screen and (min-width: 1023px) {
.selector,
.topLevel { /* ruleset inside nested media was extended */
color: blue;
}
}
Duplication Detection
Currently there is no duplication detection.
Example:
.alert-info,
.widget {
/* declarations */
}
.alert:extend(.alert-info, .widget) {}
Outputs
.alert-info,
.widget,
.alert,
.alert {
/* declarations */
}
Use Cases for Extend
Classic Use Case
The classic use case is to avoid adding a base class. For example, if you have
.animal {
background-color: black;
color: white;
}
and you want to have a subtype of animal which overrides the background color then you have two options, firstly change your HTML
<a class="animal bear">Bear</a>
.animal {
background-color: black;
color: white;
}
.bear {
background-color: brown;
}
or have simplified html and use extend in your less. e.g.
<a class="bear">Bear</a>
.animal {
background-color: black;
color: white;
}
.bear {
&:extend(.animal);
background-color: brown;
}
Reducing CSS Size
Mixins copy all of the properties into a selector, which can lead to unnecessary duplication. Therefore you can use extends instead of mixins to move the selector up to the properties you wish to use, which leads to less CSS being generated.
Example - with mixin:
.my-inline-block() {
display: inline-block;
font-size: 0;
}
.thing1 {
.my-inline-block;
}
.thing2 {
.my-inline-block;
}
Outputs
.thing1 {
display: inline-block;
font-size: 0;
}
.thing2 {
display: inline-block;
font-size: 0;
}
Example (with extends):
.my-inline-block {
display: inline-block;
font-size: 0;
}
.thing1 {
&:extend(.my-inline-block);
}
.thing2 {
&:extend(.my-inline-block);
}
Outputs
.my-inline-block,
.thing1,
.thing2 {
display: inline-block;
font-size: 0;
}
Combining Styles / A More Advanced Mixin
Another use-case is as an alternative for a mixin - because mixins can only be used with simple selectors, if you have two different blocks of html, but need to apply the same styles to both you can use extends to relate two areas.
Example:
li.list > a {
// list styles
}
button.list-style {
&:extend(li.list > a); // use the same list styles
}
Merge
Combine properties
The merge feature allows for aggregating values from multiple properties into a comma or space separated list under a single property. merge is useful for properties such as background and transform.
Comma
Append property value with comma
Released v1.5.0
Example:
.mixin() {
box-shadow+: inset 0 0 10px #555;
}
.myclass {
.mixin();
box-shadow+: 0 0 20px black;
}
Outputs
.myclass {
box-shadow: inset 0 0 10px #555, 0 0 20px black;
}
Space
Append property value with space
Released v1.7.0
Example:
.mixin() {
transform+_: scale(2);
}
.myclass {
.mixin();
transform+_: rotate(15deg);
}
Outputs
.myclass {
transform: scale(2) rotate(15deg);
}
To avoid any unintentional joins, merge requires an explicit + or +_ flag on each join pending declaration.
Mixins
"mix-in" properties from existing styles
You can mix-in class selectors and id selectors, e.g.
.a, #b {
color: red;
}
.mixin-class {
.a();
}
.mixin-id {
#b();
}
which results in:
.a, #b {
color: red;
}
.mixin-class {
color: red;
}
.mixin-id {
color: red;
}
Historically, the parentheses in a mixin call are optional, but optional parentheses are deprecated and will be required in a future release.
.a();
.a; // currently works, but deprecated; don't use
.a (); // white-space before parentheses is also deprecated
Mixins With Parentheses
If you want to create a mixin but you do not want that mixin to be in your CSS output, put parentheses after the mixin definition.
.my-mixin {
color: black;
}
.my-other-mixin() {
background: white;
}
.class {
.my-mixin();
.my-other-mixin();
}
outputs
.my-mixin {
color: black;
}
.class {
color: black;
background: white;
}
Selectors in Mixins
Mixins can contain more than just properties, they can contain selectors too.
For example:
.my-hover-mixin() {
&:hover {
border: 1px solid red;
}
}
button {
.my-hover-mixin();
}
Outputs
button:hover {
border: 1px solid red;
}
Namespaces
If you want to mixin properties inside a more complicated selector, you can stack up multiple ids or classes.
#outer() {
.inner {
color: red;
}
}
.c {
#outer.inner();
}
Note: legacy Less syntax allows > and whitespace between namespaces and mixins. This syntax is deprecated and may be removed. Currently, these do the same thing.
#outer > .inner(); // deprecated
#outer .inner(); // deprecated
#outer.inner(); // preferred
Namespacing your mixins like this reduces conflicts with other library mixins or user mixins, but can also be a way to "organize" groups of mixins.
Example:
#my-library {
.my-mixin() {
color: black;
}
}
// which can be used like this
.class {
#my-library.my-mixin();
}
Guarded Namespaces
If a namespace has a guard, mixins defined by it are used only if the guard condition returns true. A namespace guard is evaluated exactly the same as a guard on a mixin, so the following two mixins work the same way:
#namespace when (@mode = huge) {
.mixin() { /* */ }
}
#namespace {
.mixin() when (@mode = huge) { /* */ }
}
The default function is assumed to have the same value for all nested namespaces and mixin. The following mixin is never evaluated; one of its guards is guaranteed to be false:
#sp_1 when (default()) {
#sp_2 when (default()) {
.mixin() when not(default()) { /* */ }
}
}
The !important keyword
Use the !important keyword after mixin call to mark all properties inherited by it as !important:
Example:
.foo (@bg: #f5f5f5; @color: #900) {
background: @bg;
color: @color;
}
.unimportant {
.foo();
}
.important {
.foo() !important;
}
Results in:
.unimportant {
background: #f5f5f5;
color: #900;
}
.important {
background: #f5f5f5 !important;
color: #900 !important;
}
Parametric Mixins
How to pass arguments to mixins
Mixins can also take arguments, which are variables passed to the block of selectors when it is mixed in.
For example:
.border-radius(@radius) {
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
border-radius: @radius;
}
And here's how we can mix it into various rulesets:
#header {
.border-radius(4px);
}
.button {
.border-radius(6px);
}
Parametric mixins can also have default values for their parameters:
.border-radius(@radius: 5px) {
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
border-radius: @radius;
}
We can invoke it like this now:
#header {
.border-radius();
}
And it will include a 5px border-radius.
You can also use parametric mixins which don't take parameters. This is useful if you want to hide the ruleset from the CSS output, but want to include its properties in other rulesets:
.wrap() {
text-wrap: wrap;
white-space: -moz-pre-wrap;
white-space: pre-wrap;
word-wrap: break-word;
}
pre { .wrap() }
Which would output:
pre {
text-wrap: wrap;
white-space: -moz-pre-wrap;
white-space: pre-wrap;
word-wrap: break-word;
}
Parameter separators
Parameters are currently either semicolon or comma separated.
Originally, parameters were only separated by commas, but the semi-colon was later added to support passing comma-separated list values to single arguments.
- two arguments and each contains comma separated list:
.name(1, 2, 3; something, else), - three arguments and each contains one number:
.name(1, 2, 3), - use dummy semicolon to create mixin call with one argument containing comma separated css list:
.name(1, 2, 3;), - comma separated default value:
.name(@param1: red, blue;). - As of Less 4.0, you can wrap a list value using a paren escape [
~()], e.g..name(@param1: ~(red, blue)). This is similar to the quote escape syntax:~"quote"
Overloading mixins
It is legal to define multiple mixins with the same name and number of parameters. Less will use properties of all that can apply. If you used the mixin with one parameter e.g. .mixin(green);, then properties of all mixins with exactly one mandatory parameter will be used:
.mixin(@color) {
color-1: @color;
}
.mixin(@color, @padding: 2) {
color-2: @color;
padding-2: @padding;
}
.mixin(@color, @padding, @margin: 2) {
color-3: @color;
padding-3: @padding;
margin: @margin @margin @margin @margin;
}
.some .selector div {
.mixin(#008000);
}
compiles into:
.some .selector div {
color-1: #008000;
color-2: #008000;
padding-2: 2;
}
Named Parameters
A mixin reference can supply parameters values by their names instead of just positions. Any parameter can be referenced by its name and they do not have to be in any special order:
.mixin(@color: black; @margin: 10px; @padding: 20px) {
color: @color;
margin: @margin;
padding: @padding;
}
.class1 {
.mixin(@margin: 20px; @color: #33acfe);
}
.class2 {
.mixin(#efca44; @padding: 40px);
}
compiles into:
.class1 {
color: #33acfe;
margin: 20px;
padding: 20px;
}
.class2 {
color: #efca44;
margin: 10px;
padding: 40px;
}
The @arguments Variable
@arguments has a special meaning inside mixins, it contains all the arguments passed, when the mixin was called. This is useful if you don't want to deal with individual parameters:
.box-shadow(@x: 0, @y: 0, @blur: 1px, @color: #000) {
-webkit-box-shadow: @arguments;
-moz-box-shadow: @arguments;
box-shadow: @arguments;
}
.big-block {
.box-shadow(2px, 5px);
}
Which results in:
.big-block {
-webkit-box-shadow: 2px 5px 1px #000;
-moz-box-shadow: 2px 5px 1px #000;
box-shadow: 2px 5px 1px #000;
}
Advanced Arguments and the @rest Variable
You can use ... if you want your mixin to take a variable number of arguments. Using this after a variable name will assign those arguments to the variable.
.mixin(...) { // matches 0-N arguments
.mixin() { // matches exactly 0 arguments
.mixin(@a: 1) { // matches 0-1 arguments
.mixin(@a: 1, ...) { // matches 0-N arguments
.mixin(@a, ...) { // matches 1-N arguments
Furthermore:
.mixin(@a, @rest...) {
// @rest is bound to arguments after @a
// @arguments is bound to all arguments
}
Pattern-matching
Sometimes, you may want to change the behavior of a mixin, based on the parameters you pass to it. Let's start with something basic:
.mixin(@s, @color) { ... }
.class {
.mixin(@switch, #888);
}
Now let's say we want .mixin to behave differently, based on the value of @switch, we could define .mixin as such:
.mixin(dark, @color) {
color: darken(@color, 10%);
}
.mixin(light, @color) {
color: lighten(@color, 10%);
}
.mixin(@_, @color) {
display: block;
}
Now, if we run:
@switch: light;
.class {
.mixin(@switch, #888);
}
We will get the following CSS:
.class {
color: #a2a2a2;
display: block;
}
Where the color passed to .mixin was lightened. If the value of @switch was dark, the result would be a darker color.
Here's what happened:
- The first mixin definition didn't match because it expected
darkas the first argument. - The second mixin definition matched, because it expected
light. - The third mixin definition matched because it expected any value.
Only mixin definitions which matched were used. Variables match and bind to any value. Anything other than a variable matches only with a value equal to itself.
We can also match on arity, here's an example:
.mixin(@a) {
color: @a;
}
.mixin(@a, @b) {
color: fade(@a, @b);
}
Now if we call .mixin with a single argument, we will get the output of the first definition, but if we call it with two arguments, we will get the second definition, namely @a faded to @b.
Using Mixins as Functions
Selecting properties and variables from mixin calls
Property / value accessors
Released v3.5.0
Starting in Less 3.5, you can use property/variable accessors to select a value from an evaluated mixin's rules. This can allow you to use mixins similar to functions.
Example:
.average(@x, @y) {
@result: ((@x + @y) / 2);
}
div {
// call a mixin and look up its "@result" value
padding: .average(16px, 50px)[@result];
}
Results in:
div {
padding: 33px;
}
Overriding mixin values
If you have multiple matching mixins, all rules are evaluated and merged, and the last matching value with that identifier is returned. This is similar to the cascade in CSS, and it allows you to "override" mixin values.
// library.less
#library() {
.mixin() {
prop: foo;
}
}
// customize.less
@import "library";
#library() {
.mixin() {
prop: bar;
}
}
.box {
my-value: #library.mixin[prop];
}
Outputs:
.box {
my-value: bar;
}
Unnamed lookups
If you don't specify a lookup value in [@lookup] and instead write [] after a mixin or ruleset call, all values will cascade and the last declared value will be selected.
Meaning: the averaging mixin from the above example could be written as:
.average(@x, @y) {
@result: ((@x + @y) / 2);
}
div {
// call a mixin and look up its final value
padding: .average(16px, 50px)[];
}
The output is the same:
div {
padding: 33px;
}
The same cascading behavior is true for rulesets or variables aliased to mixin calls.
@dr: {
value: foo;
}
.box {
my-value: @dr[];
}
This outputs:
.box {
my-value: foo;
}
Unlocking mixins & variables into caller scope
DEPRECATED - Use Property / Value Accessors
Variables and mixins defined in a mixin are visible and can be used in caller's scope. There is only one exception: a variable is not copied if the caller contains a variable with the same name (that includes variables defined by another mixin call). Only variables present in callers local scope are protected. Variables inherited from parent scopes are overridden.
Note: this behavior is deprecated, and in the future, variables and mixins will not be merged into the caller scope in this way.
Example:
.mixin() {
@width: 100%;
@height: 200px;
}
.caller {
.mixin();
width: @width;
height: @height;
}
Results in:
.caller {
width: 100%;
height: 200px;
}
Variables defined directly in callers scope cannot be overridden. However, variables defined in callers parent scope is not protected and will be overridden:
.mixin() {
@size: in-mixin;
@definedOnlyInMixin: in-mixin;
}
.class {
margin: @size @definedOnlyInMixin;
.mixin();
}
@size: globaly-defined-value; // callers parent scope - no protection
Results in:
.class {
margin: in-mixin in-mixin;
}
Finally, mixin defined in mixin acts as return value too:
.unlock(@value) { // outer mixin
.doSomething() { // nested mixin
declaration: @value;
}
}
#namespace {
.unlock(5); // unlock doSomething mixin
.doSomething(); //nested mixin was copied here and is usable
}
Results in:
#namespace {
declaration: 5;
}
Recursive Mixins
Creating loops
In Less a mixin can call itself. Such recursive mixins, when combined with Guard Expressions and Pattern Matching, can be used to create various iterative/loop structures.
Example:
.loop(@counter) when (@counter > 0) {
.loop((@counter - 1)); // next iteration
width: (10px * @counter); // code for each iteration
}
div {
.loop(5); // launch the loop
}
Output:
div {
width: 10px;
width: 20px;
width: 30px;
width: 40px;
width: 50px;
}
A generic example of using a recursive loop to gene