Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create multiple background using SASS mixin

Tags:

css

sass

I'm trying to create a mixin in Sass to generate multiple background, problem is the number of background is unknow, it's can be 3, 4 or even 5. Here what I try and fail.

@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 output:

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'm still learing SASS. Can someone enlighten me please.

like image 324
VK Da NINJA Avatar asked Mar 10 '23 03:03

VK Da NINJA


2 Answers

You're on the right track! But your syntax and logic are slightly off. Here's 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;
}

That seems to return what you're looking for. Here are the official docs on list functions - I always forget one or two, may be useful for you too.

Also, since you mentioned you're new to sass - check out Sassmeister if you haven't already. It's a handy little sandbox for quickly prototyping and trying things out in sass; similar to Codepen but a bit more specialized. It's what I used to experiment with this question.

like image 158
jack Avatar answered Mar 21 '23 11:03

jack


This is a cleaner answer, I believe.

@mixin image-resolve($image) {
  $images: ();

   @each $i in $image {
     $path: ();

     $images: append($images, $path, comma);
   }

 background-image: $images;
}
like image 37
chris_r Avatar answered Mar 21 '23 10:03

chris_r