pass a list to a mixin as a single argument with SASS
I like to make mixins with SASS that help me make good cross-browser compatibility. I want to make a mixin that looks like this:
@mixin box-shadow($value) {
box-shadow: $value;
-webkit-box-shadow: $value;
-moz-box-shadow: $value;
}
to which I can pass something like this:
@include box-shadow(inset -2px -2px 2px rgba(0,0,0,0.5), inset 1px 1px 2px rgba(255,255,255,0.5), inset 0px 0px 0px 1px #ff800f);
with the result being something like this:
box-shadow: inset -2px -2px 2px rgba(0,0,0,0.5), inset 1px 1px 2px rgba(255,255,255,0.5),inset 0px 0px 0px 1px #ff800f;
-moz-box-shadow: inset -2px -2px 2px rgba(0,0,0,0.5), inset 1px 1px 2px rgba(255,255,255,0.5),inset 0px 0px 0px 1px #ff800f;
-webkit-box-shadow: inset -2px -2px 2px rgba(0,0,0,0.5), inset 1px 1px 2px rgba(255,255,255,0.5),inset 0px 0px 0px 1px #ff800f;
However, This doesn't work because the complier thinks I am trying to pass the mixin 3 arguments. box-shadow takes a variable number of comma separated bits, so I can't just define a mixin like box-shadow($1,$2,$3)
.
I tried passing
@include box-shadow("inset -2px -2px 2px rgba(0,0,0,0.5), inset 1px 1px 2px rgba(255,255,255,0.5), inset 0px 0px 0px 1px #ff800f");
and it compiled, but didn't actually render the styles.
Any tips on how to resolve this?
Variable Arguments
Sometimes it makes sense for a mixin to take an unknown number of arguments. For example, a mixin for creating box shadows might take any number of shadows as arguments. For these situations, Sass supports “variable arguments,” which are arguments at the end of a mixin declaration that take all leftover arguments and package them up as a list. These arguments look just like normal arguments, but are followed by .... For example:
@mixin box-shadow($shadows...) {
-moz-box-shadow: $shadows;
-webkit-box-shadow: $shadows;
box-shadow: $shadows;
}
.shadows {
@include box-shadow(0px 4px 5px #666, 2px 6px 10px #999);
}
via: http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#variable_arguments
SASS 3.1 or less
Note: If you're using SASS 3.2+ then use the Variable Arguments feature as rzar suggests.
Just use string interpolation in the mixin itself, like so:
@mixin box-shadow($value) {
-webkit-box-shadow: #{$value}; // #{} removes the quotation marks that
-moz-box-shadow: #{$value}; // cause the CSS to render incorrectly.
box-shadow: #{$value};
}
// ... calling it with quotations works great ...
@include box-shadow("inset -2px -2px 2px rgba(0,0,0,0.5), inset 1px 1px 2px rgba(255,255,255,0.5), inset 0px 0px 0px 1px #ff800f");
Thanks for the tip Ryan.