In the following scenario I need to support as many browsers as possible.
I am building a SCSS @mixin
that prefixes background-image
with vendor prefixes, but also listens to see if a linear-gradient
is declared, and if it is, then prefix that as well.
My code looks like this:
@function str-coerce($string) {
@return inspect($string);
}
@function str-replace($string, $find, $replace: "") {
$index: str-index($string, $find);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($find)), $find, $replace);
}
@return $string;
}
@mixin background-image($values...) {
$vendors: (-webkit-, -moz-, -o-);
@each $vendor in $vendors {
$string: str-coerce($values);
@if (str-index($string, "linear-gradient")) {
$string: str-replace($string, "linear-gradient", #{$vendor + "linear-gradient"});
@if (str-index($vendor, "-o-")) {
$vendor: str-replace($vendor, "-o-");
}
#{$vendor + "background-image"}: $string;
} @else {
@if not (str-index($vendor, "-o-")) {
#{$vendor + "background-image"}: $values;
}
}
}
background-image: $values;
}
Usage and output looks like this:
// usage
.foo {
@include background-image(url("../example.svg"));
}
.bar {
@include background-image(linear-gradient(45deg, red, blue));
}
// output
.foo {
-webkit-background-image: url("../example.svg");
-moz-background-image: url("../example.svg");
background-image: url("../example.svg");
}
.bar {
-webkit-background-image: (-webkit-linear-gradient(45deg, red, blue),);
-moz-background-image: (-moz-linear-gradient(45deg, red, blue),);
background-image: (-o-linear-gradient(45deg, red, blue),);
background-image: linear-gradient(45deg, red, blue);
}
My question is, what is going wrong in my type coercion that is causing my linear-gradient
vendor prefixes to be wrapped in brackets and followed with a comma? e.g. (-moz-linear-gradient(45deg, red, blue),)
.