22

I currently have a mixins.less file, where almost all mixins are basically the same:

.border-radius(@radius) {
  -webkit-border-radius: @radius;
   -khtml-border-radius: @radius;
     -moz-border-radius: @radius;
          border-radius: @radius;
}

.box-shadow(@value) {
  -webkit-box-shadow: @value;
   -khtml-box-shadow: @value;
     -moz-box-shadow: @value;
          box-shadow: @value;
}

Is there a way to create some kind of generic mixin, that I could call like this:

.vendor('border-radius', '3px');
.vendor('box-shadox', '10px 10px');

and which would produce the same result as above?

BenMorel
  • 34,448
  • 50
  • 182
  • 322

1 Answers1

40

Notice:

The recommendation is to stop rely on this technique and consider using a dedicated prefixing tool (e.g. Autoprefixer, -prefix-free etc.). Hardcoding vendor prefixes via CSS pre-processor mixins (Less, SCSS or whatever) is a pure anti-pattern these days and considered harmful. Auto-prefixing tools will make your code clean, readable, future-proof and easily maintainable/customizable.

See for example: less-plugin-autoprefix


Original answer:

Well, currently LESS does not support "property name interpolation" so you cannot use a variable in property names. There's a hack however: How to pass a property name as an argument to a mixin in less So if you don't mind "dummy" properties in the output CSS, here we go:

.property_(@property, @value) {
    _: ~"; @{property}:" @value;
}

.vendor(@property, @value) {
    .property_('-webkit-@{property}', @value);
    .property_( '-khtml-@{property}', @value);
    .property_(   '-moz-@{property}', @value);
    .property_(          @property,   @value);
}

#usage {
    .vendor(border-radius, 3px);
    .vendor(box-shadow, 10px 10px);
}

Output:

#usage {
  _: ; -webkit-border-radius: 3px;
  _: ; -khtml-border-radius: 3px;
  _: ; -moz-border-radius: 3px;
  _: ; border-radius: 3px;
  _: ; -webkit-box-shadow: 10px 10px;
  _: ; -khtml-box-shadow: 10px 10px;
  _: ; -moz-box-shadow: 10px 10px;
  _: ; box-shadow: 10px 10px;
}

Update:

Less v1.6.0 introduced Property Interpolation feature so now you don't need any hacks anymore:

.vendor(@property, @value) {
    -webkit-@{property}: @value;
     -khtml-@{property}: @value;
       -moz-@{property}: @value;
            @{property}: @value;
}

#usage {
    .vendor(border-radius, 3px);
    .vendor(box-shadow, 10px 10px);
}
Community
  • 1
  • 1
seven-phases-max
  • 11,765
  • 1
  • 45
  • 57