LESS allows parametric mixins, such as:
.transition(@property, @duration){
transition: @property @duration;
-moz-transition: @property @du
Note: This answer is not added with the intention of saying the existing answers are incorrect or obsolete. All the answers are valid and would still work. This one just provides a different method which in my opinion is a bit more complex but also more flexible in terms of how each argument can be mentioned as key-value pairs.
Advantages of using this method: This method would become more useful when there is a need to perform any extra operation on the values (say like adding unit as deg, px or performing any extra math operations etc) or dynamically adding the vendor prefixes for the @property also. For example there are times when you might want to pass only transform as an input property to the mixin but want to add -webkit-transform for the -webkit-transition and -moz-transform for the -moz-transition etc.
In this method, we make use of the ... feature which allows us to pass variable number of arguments to a mixin, loop over each argument that is passed, extract the name of the property along with the additional parameters (like duration, degree of rotation etc) and then use the merge feature that is provided by Less to concatenate the values specified for the property.
.transition(@args...){
.loop-args(@argCount) when (@argCount > 0) {
.loop-args(@argCount - 1);
@arg: extract(@args, @argCount);
@property: extract(@arg,1);
@duration: extract(@arg,2);
-webkit-transition+: @property @duration;
-moz-transition+: @property @duration;
-o-transition+: @property @duration;
transition+: @property @duration;
}
.loop-args(length(@args));
}
div{
.transition(background, 1s; border-color, 2s; color, 2s);
}
.transform(@args...){
.loop-args(@argCount) when (@argCount > 0) {
.loop-args(@argCount - 1);
@arg: extract(@args, @argCount);
@property: extract(@arg,1);
@param: extract(@arg,2);
-webkit-transform+_: ~"@{property}(@{param})";
-moz-transform+_: ~"@{property}(@{param})";
-o-transform+_: ~"@{property}(@{param})";
transform+_: ~"@{property}(@{param})";
}
.loop-args(length(@args));
}
div#div2{
.transform(rotate, 20deg; scale, 1.5; translateX, 10px);
}
The above code when compiled would produce the below output:
div {
-webkit-transition: background 1s, border-color 2s, color 2s;
-moz-transition: background 1s, border-color 2s, color 2s;
-o-transition: background 1s, border-color 2s, color 2s;
transition: background 1s, border-color 2s, color 2s;
}
div#div2 {
-webkit-transform: rotate(20deg) scale(1.5) translateX(10px);
-moz-transform: rotate(20deg) scale(1.5) translateX(10px);
-o-transform: rotate(20deg) scale(1.5) translateX(10px);
transform: rotate(20deg) scale(1.5) translateX(10px);
}
Related Answer: