Search code examples
compass-sass

Compass sprite images across multiple style sheets


Is there a way to get compass to generate a sprite sheet from images across different style sheets?

The tutorial talks about generating sprites from a bunch of images in the folder and then using it in 1 style sheet. But to me, it seems counter intuitive to have to use the following in all my stylesheets that uses the sprite sheet:

@import "icon/*.png";
@include all-icon-sprites;

I would prefer to have different images set for each sprite sheet, and then some how mark them for sprite generation so that compass can collect them into a sprite and then update the css to reflect that.


Solution

  • Compass only generates one sprite per directory. That's good because it can be cached by browsers eliminating the need to fetch it if you use it on multiple pages. You can use that sprite over and over even selectively using Selector Control which is covered in the tutorial you referenced.

    Imagine that in your image folder there are four icons:

    • images/icon/apple.png
    • images/icon/banana.png
    • images/icon/basketball.png
    • images/icon/football.png

    In a stylesheet called fruits.sass, you import all the icons and only use the apple and banana icons.

    @import "icon/*.png";
    
    .fruits
      .banana
        +icon-sprite(banana)
      .apple
        +icon-sprite(apple)
    

    In a stylesheet called sports.sass, you import all the icons and only use basketball and football icons.

    @import "icon/*.png";
    
    .sports
      .football
        +icon-sprite(football)
      .basketball
        +icon-sprite(basketball)
    

    When you compile, one sprite named something like icon-sjargon1.png will be generated in images.

    • images/icon/apple.png
    • images/icon/banana.png
    • images/icon/basketball.png
    • images/icon/football.png
    • images/icon-sjargon1.png

    Your generated fruits.css will look something like:

    .icon-sprite,
    .fruits .banana,
    .fruits .apple { background: url('/images/icon-sjargon1.png') no-repeat; }
    
    .fruits .banana { background-position: 0 -20px; }
    .fruits .apple { background-position: 0 0; }
    

    Your generated sports.css will look like:

    .icon-sprite,
    .sports .football,
    .sports .basketball { background: url('/images/icon-sjargon1.png') no-repeat; }
    
    .sports .football { background-position: 0 -60px; }
    .sports .basketball { background-position: 0 -40px; }