csssass

SCSS/SASS dynamic background image based on class name


I was looking for a "sassy" way to do something like this:

.btn-save {
  background: image-url('save.svg');
}

.btn-load {
  background: image-url('load.svg');
}

.btn-back {
  background: image-url('back.svg');
}

Is there a way I could grab the last part of the class name and pass it to a function to load the appropriate SVG icon? I was thinking it'd look something like:

@function load-svg($svg-name) {
  background: image-url($svg-name + ".svg");
}

.btn-* {
  // I'm not sure how to get the $svg-name here
  load-svg($svg-name);
}

Solution

  • If you want a DRY approach you could pass a list to a mixin

    @mixin setSVGButton($svgs) {
      @each $svg in $svgs {
        .btn-#{$svg} {
          background-image: url(#{$svg}.svg);
        }
      } 
    }
    
    
    @include setSVGButton(('save', 'load', 'back'));