best way to do sprites in SASS

Asked

Viewed 148 times

1

I am making a Sprite with Sass as follows below, but I would like to know if this way is correct or not, or if there is another better way.

$sprites: bovino, suino, aves, embutidos, congelados, ovinos, laticinios;


.icon-sprite {
    background-color: transparent;
    display: inline-block;
    white-space: nowrap;
}

// insert the icons
@each $icon in $sprites {
    [class*='icon-#{$icon}'] {
        background-image: url(../img/icon-#{$icon});
        background-repeat: no-repeat;
        width: 55px;
        height: 55px;

        @if $icon == "bovino" {
            background-position: 0 -1px;
        }
        @else if $icon == "suino" {
            background-position: 0 -117px;
        }
        @else if $icon == "aves" {
            background-position: 0 -175px;
        }
        @else if $icon == "embutidos" {
            background-position: 0 -235px;
        }
        @else if $icon == "congelados" {
            background-position: 0 -296px;
        }
        @else if $icon == "ovinos" {
            background-position: 0 -60px;
        }
        @else if $icon == "laticinios" {
            background-position: 0 -355px;
        }

    }

}
  • Is there a logic in the size of your sprites, or are all of different sizes?

2 answers

0

You can use maps and instead of doing this whole roll of ifs and elseifs you just add in map the new icon.

$sprites: (
  'bovino':     (0 -1px),
  'suino':      (0 -117px),
  'aves':       (0 -175px),
  'embutidos':  (0 -235px),
  'congelados': (0 -296px),
  'ovinos':     (0 -60px),
  'laticinios': (0 -355px)
);

%icon {
  display: inline-block;
  width: 55px;
  height: 55px;
  white-space: nowrap;
  background-repeat: no-repeat;
  background-color: transparent;
}

@each $sprite, $pos in $sprites {
  .icon-#{$sprite} {
    @extend %icon;
    background-image: url(../img/icon-#{$sprite});
    background-position: $pos;
  }
}

0

There is the grunt-spritesmith if you use Grunt to compile your SASS. The good thing about this Grunt task is that it generates a SASS file with reference to all "pieces" of Prite, providing variables - which greatly simplifies Prite maintenance in the future (removal or insertion of new icons will be easily handled with a new compilation of SASS files).

To know more about the package: https://github.com/Ensighten/grunt-spritesmith

A good tutorial to make the tool work (is in Less, but is easily adaptable): http://emlyn.net/post/spritesmith-tutorial/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.