Creating multiple background images using the SASS mixin
I am trying to create a mixin in Sass to generate multiple backgrounds, the problem is the amount of background is unknown, it could be 3, 4 or even 5. Here I am trying and failing.
@mixin multiBg($page: index, $sec: sec01,$from: 1, $to: 3, $type: jpg){
$url: (); // i'm try to create a empty array first
$newUrl: null; // and an empty variable
@for $i from $from through $to {
$newUrl: append($url, url(../img/#{$page}/#{$sec}_bg0#{$i}.#{$type})); // then append value to variable;
}
background: $newUrl;
}
#sec05 {
@include multiBg(index,sec05);
}
current output:
background: url(../img/index/sec05_bg03.jpg);
Expected Result:
background: url(../img/sec05_bg01.jpg),url(../img/sec05_bg02.jpg), url(../img/sec05_bg03.jpg);
I don't know how to fix this problem since I am still lying with SASS. Can someone enlighten me please.
source to share
You are on the right track! But your syntax and logic are slightly off. This is what I came up with:
@mixin multiBg($page: index, $sec: sec01, $from: 1, $to: 5, $type: jpg) {
$url_list: ();
@for $i from $from through $to {
// I broke constructing the url and adding it to the set into two steps here.
// We could do this all at once, but separating it can make it easier to read.
// First, generate the url.
$url_string: url(../img/#{$page}/#{$sec}_bg0#{$i}.#{$type});
// Then add it to the list (the 'comma' part is important)
$url_list: append($url_list, $url_string, comma);
}
// Done looping? Output the final list!
background-image: $url_list;
}
This is similar to what you are looking for. Here are the official docs on list functions - I always forget one or two, might be helpful for you too.
Also, since you mentioned that you are new to sass - check out Sassmeister if you haven't already. It's a handy little sandbox for rapid prototyping and awakening in essence; similar to Codepen , but slightly more specialized. This is what I used to experiment with this question.
source to share