Overriding mixins in LESS

1k views Asked by At

when defining a mixin multiple times in LESS, and later calling that mixin as follows

.background-color() {
    background: red;
}

.background-color() {
    background: yellow;
}

body {
    .background-color;
}

the result will be a combined output from all the defined mixins

body {
  background: red;    // << output from mixin #1
  background: yellow; // << output from mixin #2
}

while when you apply the same scenario in both Sass & Stylus ( using their own syntax of course ), when you call a mixin that is defined multiple times across your stylesheets, Only the last defined one will be executed ( it will override all previously defined mixins ) as follows.

result Sass and Stylus

body {
  background: yellow; // << output from mixin #2
}

how can I override a mixin in LESS so that the output will be from the last defined mixin ?

1

There are 1 answers

0
Bass Jobsen On

You can not override them, alternatively use a variable to define the 'background-color'. For Less variables the last declared win.

Also read Pattern-matching

In Less all matching mixins are compiled in the source. You can use namespace to prevent name collisions, for instance:

#ns1 {
.background-color() {
    background: red;
}
}

#ns2 {
.background-color() {
    background: yellow;
}
}

than you can use:

body {
    #ns2 > .background-color;
}

Double properties are also not removed to make some browser hacks possible, example:

#myElement {
    width: 300px;
    width: 500px\9;
}

To find a solution for your use case you should reformulate your question and explain why you have these same named mixins in the first place.