French version Spanish version

SmartSprites (Alpha!)

CSS Sprite Generator Done Right

What is SmartSprites?

SmartSprites will let you easily introduce and maintain CSS sprites in your designs. SmartSprites parses special directives you can insert into your original CSS to mark individual images to be turned into sprites. It then builds sprite images from the collected images and automatically inserts the required CSS properties into your style sheet, so that the sprites are used instead of the individual images.

SmartSprites parses special directives you can insert into your original CSS to mark individual images to be turned into sprites. It then builds sprite images from the collected images and automatically inserts the required CSS properties to your style sheet, so that the sprites are used instead of the individual images.

In other words, no tedious copying & pasting to your CSS when adding, removing or changing sprited images. Just work with your CSS and original images as usual and have SmartSprites automatically transform them to the sprite-powered version when necessary.

Other features of SmartSprites:

  • Alpha release: Please bear with, or better -- report, any issues you have.
  • (NEW!)Full support for GIF and PNG8/24: SmartSprites can create sprites in both GIF and PNG8/24 formats, including transparency. Moreover, it can optimize the PNG output so that PNG24 is used only when needed.
  • "Spriting" x- and y-repeated images: SmartSprites supports turning background images repeated along x and y axes into sprites.
  • Right and bottom image position: SmartSprites can turn into sprites also background images that are positioned to the right or bottom of the container.
  • Vertical and horizontal sprites: SmartSprites can create both vertically and horizontally laid-out sprites, required to support x- and y-repeated and right and bottom-positioned backgrounds.
  • Customized sprite margins: With SmartSprites you can customize left, right, top and bottom margins of each individual sprite for pixel perfect positioning.
  • Multiple sprite images and CSS files: SmartSprites can process multiple CSS files and produce many different sprites in one step (e.g. one vertical for icons, another horizontal one for tabs).
  • (NEW!)Support for hi-DPI displays using the sprite-scale property.
  • Special support for Internet Explorer 6: SmartSprites can generate IE6-friendly PNG8 sprites preserving transparency wherever possible. Optionally, a matte color can be set for each sprite separately.
  • (NEW!)CSS- and document-root-relative image paths: Paths to individual images and the resulting sprites can be specified both relatively to the CSS file or in an absolute fashion, relatively to the provided document root directory.
  • (NEW!)Integrated with JAWR: SmartSprites is integrated into JAWR, a complete CSS/JS bundling and compression solution for Java.
  • Easy integration with build systems: Transparent processing is the driving force behind SmartSprites, using a dedicated Ant task (NEW!)it can be very easily integrated into automated build scripts.
  • (NEW!)Eclipse plugin available to build sprites directly from your IDE.
  • (NEW!)Maven plugin available to build sprites as part of your Maven builds.
  • Open Source BSD License: You can use and contribute to SmartSprites no matter whether you're doing an Open Source or a commercial project.

Using SmartSprites

  1. Start with preparing your design (HTML, CSS, images) the usual way. Use background-image to attach images like icons, logos or e.g. x- or y-repeated backgrounds. You'll probably end up with a CSS pattern along the lines of this: #web { width: 17px; height: 17px; background-repeat: no-repeat; background-image: url(../img/web.gif); } #logo { width: 50px; height: 50px; background-repeat: no-repeat; background-position: top right; background-image: url(../img/logo.png); } #main-box { background-repeat: repeat-x; background-position: 5px left; background-image: url(../img/top-frame.gif); } When you've verified that the original design works as indented, you're ready to annotate it with SmartSprite's directives.
  2. Annotate your CSS with SmartSprites directives. SmartSprites directives must be enclosed between /** and */ characters (CSS comments), which will make them transparent to the browser, when you're working on your original CSS. Inside the comments, the directives follow the common CSS syntax of property: value. After adding annotations, the original CSS will look like this (directives highlighted):

    /** sprite: mysprite; sprite-image: url('../img/mysprite.png'); sprite-layout: vertical */ #web { width: 17px; height: 17px; background-repeat: no-repeat; background-image: url(../img/web.gif); /** sprite-ref: mysprite; */ } #logo { width: 50px; height: 50px; background-repeat: no-repeat; background-position: top right; background-image: url(../img/logo.png); /** sprite-ref: mysprite; sprite-alignment: right */ } #main-box { background-repeat: repeat-x; background-position: 5px left; background-image: url(../img/top-frame.gif); /** sprite-ref: mysprite; sprite-alignment: repeat; sprite-margin-top: 5px */ }

    The first directive (in red) tells SmartSprites that there will be one sprite whose name is mysprite, which should be saved to ../img/mysprite.png relative to the CSS file. Images in this sprite will be laid out vertically (on top of each other).

    The directive for the #web rule instructs SmartSprites to add image located at ../img/web.gif to the mysprite sprite. SmartSprites will also replace that line of CSS with properties referring to the sprite it created.

    The directive for the #logo rule tells SmartSprites to add ../img/logo.png to the same sprite and align it to the right edge of the sprite image. This way, the image can be positioned towards the right edge of the box to achieve the same effect as with the original background-position: top right declaration.

    Finally, the directive for the #main-box rule instructs SmartSprites to repeat the ../img/top-frame.png across the full width of the sprite image, so that the effect of background-repeat: repeat-x can be preserved. Additionally, SmartSprites will offset the image from the bottom edge of the neighbouring image in the sprite by 5px, so that the effect of background-position: 5px top is also preserved.

    Below is a detailed description of SmartSprites directives, which you may find a little heavy, but it will allow you to use all the power of SmartSprites. There are two types of SmartSprites directives:

    1. Sprite Image Directive, marked in red, is used to declare one sprite image, which merges some number of individual images. Sprite image directive must start with /** sprite: and must be contained in a single line. A single CSS file can contain any number of sprite image directives. The sprite image directive specifies the following properties:

      • Sprite ID, syntax: sprite: unique-id, required. A unique identifier by which the sprite image will be referred to. For each unique sprite id, SmartSprites will create one sprite image.
      • Sprite image location, syntax: sprite-image: url('path/name.(png | gif | jpg)'), required. CSS file-relative path to the sprite image to be created. SmartSprites will infer the format of the image based on the extension used. Currently supported are: gif, png and jpg.

        The path can contain a number of variable references of the form ${variable}. The following variables are supported and will be replaced with the corresponding content:

        • sprite: Sprite ID
        • md5: MD5 hash of the sprite image file created by SmartSprites. The hash will change only if the sprite image content or file format changes.
        • date: timestamp taken at the time of sprite image generation. The timestamp will be different every time SmartSprites processing is run, even if the sprite images do not change

        The sprite image path can contain a ? character to enable query-string-based cache busting. The portion of the path from the ? character until the end of the path will be ignored when determining the actual name of the sprite image to be written to disk.

        Please note that you can put the variables anywhere in the sprite image path, e.g.

        sprite-image: url('../img/logo-${md5}.png') sprite-image: url('../${date}/${sprite}.png') sprite-image: url('../sprite.png?${md5}')
      • Sprite image layout, syntax: sprite-layout: vertical | horizontal, optional, default value: vertical. Specifies whether the individual images should be laid out in the sprite image vertically (on top of each other) or horizontally (next to each other).
      • Sprite scale, syntax: sprite-scale: number, optional, default value: 1. If the provided scale value is not 1, for each sprite reference SmartSprites will output the background-size CSS property with a value equal to the actual sprite dimensions divided by the provided scale; offsets output in the background-position property will also be divided by the scale.

        SmartSprites will accepth both integer and float values of sprite-scale. Warnings will be issued if the computed background size dimensions are not integer numbers.

        You can use the sprite-scale property to create sprite images for high-DPI displays, such as Retina. In case of Retina, you'll need to prepare the individual images in a x2 resolution and set the sprite-scale of the Retina-specific sprite image to 2.

      • Matte color, syntax: sprite-matte-color: #ff8822, optional, default value: #ffffff. Specifies the matte color that should be used to render partial transparencies on sprites saved in GIF or PNG8 formats. Note: currently only the 6-digit hexadecimal color specifications are supported. See also the PNG color depth and IE6-friendly PNG options.
      • IE6 compatibility mode, syntax: sprite-ie6-mode: auto | none, optional, default value: auto. Specifies whether an IE6-compatible image for this sprite should be generated when necessary (auto) or should not be generated at all (none). See the IE6-friendly PNG option for more details.
    2. Sprite Reference Directive, marked in orange, is used to tell SmartSprites that a specific individual image should be placed in the specified sprite image. The sprite reference directive must contain in one line, a background-image CSS property specifying a CSS file-relative path to the individual image and a CSS comment starting with /** sprite-ref: . The sprite reference directive specifies the following properties:
      • Sprite Reference, syntax: sprite-ref: sprite-id, required. A reference to one of the sprites declared by the sprite image directives. The individual image will be placed in the sprite with the provided identifier.
      • Sprite Alignment, syntax: sprite-alignment: left | right | top | bottom | center | repeat, optional, default value: left for sprites with vertical layout, top for sprites with horizontal layout. Defines the edge of the sprite image to which this individual image will be aligned. For vertically aligned sprites, the allowed values are left and right, while for horizontally aligned ones -- top and bottom. Sprite alignment can come in handy when the original background image was positioned towards the right or bottom of the box (e.g. background-position: top right).

        One special alignment value is repeat. In this case, the contents of the individual image will be repeated across the whole width of a vertical sprite or the whole height of a horizontal sprite. This will allow you to use sprites for backgrounds that have background-repeat set to repeat-x or repeat-y.

        Warning: the width (height) of the resulting sprite will be not smaller than the least common multiple of the widths of all individual images with alignment set to repeat in that vertical (horizontal) sprite. For example, if you have "repeated" individual images of widths (heights) 3px, 5px, 7px and 11px in one vertical (horizontal) sprite, the width (height) of that sprite will be 1155px. Therefore, use sprite-alignment: repeat with caution.

      • Sprite margins, syntax: sprite-margin-(left | right | top | bottom): OFFSETpx, optional, default value: 0px. The offset of this image from the left, right, top and bottom edge or the neighbouring image in the sprite. This property may be useful when the original image was not positioned exactly on the edge of the box, but had e.g. background-position: 5px left. Note: only pixel values are allowed. Shorthand version of margins property known from CSS is not yet supported here.

    When you've finished annotating your CSS with SmartSprites directives, you can have SmartSprites generate the sprite images and modified CSS files for you. Before you do that, you will need to install some software SmartSprites requires and SmartSprites itself.

  3. Obtain SmartSprites and the software it requires.

    1. Download and install Java JDK version 5 or above (JDK 6 recommended).
    2. Download SmartSprites and unpack the archive.

    If your software uses Maven, see Maven plugin.

    Now you're really ready to run SmartSprites.

  4. Run SmartSprites.

    1. On Windows: smartsprites --root-dir-path c:/example On Linux: ./smartsprites.sh --root-dir-path /home/user/example
    2. After processing completes you should see on the screen messages similar to:

      process: [java] INFO: Reading image from: C:\example\img\web.gif [java] INFO: Reading image from: C:\example\img\logo.png [java] INFO: Reading image from: C:\example\img\top-frame.gif [java] INFO: Creating sprite image of size 48 x 75 for mysprite [java] INFO: Creating CSS style sheet: C:\example\css\style-sprite.css [java] SmartSprites processing completed in 328 ms

      If you notice any line containing a warning (WARN:), please read it carefully and correct the problem. Otherwise, your design may not look like the original version.

      Upon successful completion, SmartSprites will create all the sprite images in the locations specified by the sprite image directives. Also, next to each processed CSS file, SmartSprites will create a corresponding CSS file with a -sprite suffix. The original CSS files will remain unchanged. To switch your design to CSS sprites, link these CSS files instead of the original ones in your HTML.

      For our example, the generated CSS would look similar to this:

      #web { width: 17px; height: 17px; background-repeat: no-repeat; background-image: url('../img/mysprite.png'); background-position: left -0px; } #logo { width: 50px; height: 50px; background-repeat: no-repeat; background-position: top right; background-image: url('../img/mysprite.png'); background-position: right -17px; } #main-box { background-repeat: repeat-x; background-position: 5px left; background-image: url('../img/mysprite.png'); background-position: left -64px; }

      Notice that all of the SmartSprites directives have been omitted in the generated CSS file. If you still see any of them in the output file, it means these specific directives had some syntactic or semantic errors and have been ignored. Warning messages should help you to pinpoint the problems.

      Also notice that SmartSprites currently doesn't remove the original background-position properties, but appends its own ones below to shadow them. Your design may break if you have background-position or background-image properties appearing below the line with SmartSprite's sprite reference directive.

  5. Check if your design still looks the same. Chances are, it won't right away. See FAQ for some tips.
  6. Tune global options. SmartSprites has a number of additional options you can specify in the command line invocation to further tune your designs.
    • --root-dir-path: directory in which SmartSprites processing should be done, required if css-files not specified or if output-dir-path specified, default: not specified.

      SmartSprites will process all files with the *.css extension found in root-dir-path or any subdirectory of it. For more fine-grained control over the processed CSS files, see the css-files option.

      If the provided root directory path is relative, it will be resolved against the current working directory.

    • --css-files: paths of CSS files to process, required if root-dir-path not specified, default: not specified.

      SmartSprites will process all CSS files listed using this option. If css-files is to be used together with output-dir-path, root-dir-path must also be specified so that SmartSprites can preserve the directory structure found in root-dir-path in output-dir-path. If root-dir-path and output-dir-path are used, css-files outside of root-dir-path will be ignored.

      Relative CSS file paths provided using this option will be resolved against the current working directory. Please note that SmartSprites will not expand any wildcards (like style/*.css), it assumes the expansion is performed at the command line shell level.

      To specify the list of CSS files to process in the SmartSprites Ant task, use one or more nested fileset elements. Please see the build.xml file in the distribution archive for an example.

    • --output-dir-path: output directory for processed CSS files and CSS-relative sprite images, optional, default: not specified.

      If a non-empty output-dir-path is specified, a non-empty root-dir-path must also be provided. The directory structure relative to the root-dir-path will be preserved in the output directory. E.g. if CSS files are contained in the css/base directory of root-dir-path, the processed results will be written to output-dir-path/css/base. Also, CSS-relative sprite images will be written to the output directory. Sprite images with document-root-relative URLs will be written relative to the document-root-dir-path. If the output-dir-path directory does not exist, it will be created. If the provided output directory path is relative, it will be resolved against the current working directory.

      You can leave the output-dir-path empty, in which case the CSS files will be written next to the original CSS files with the css-file-suffix, and sprite images will be written relative to the original CSS files. If you are using a non-empty output-dir-path, you might want to use an empty css-file-suffix.

    • --document-root-dir-path: Document root path for document-root-relative (starting with /) image urls in CSS, optional, default: not specified.

      All document-root-relative image and sprite URLs will be taken relative to document-root-dir-path. Also document-root-relative sprite URLs will be written relative to document-root-dir-path. You can leave this property empty if your CSS uses only CSS-relative image URLs. If the provided document root directory path is relative, it will be resolved against the current working directory.

    • --log-level: Message logging level, optional, default: INFO.

      Messages less important than log-level will not be shown. SmartSprites has 3 levels of log messages (in the increasing order of importance):

      1. INFO: information messages, can be safely ignored
      2. IE6NOTICE: notices related to possible quality loss when creating IE6-friendly sprite images, see also the IE6-friendly PNG option
      3. WARN: warnings related to syntax, IO and sprite rendering quality loss problems that may cause the converted sprite-based designs look broken
    • --sprite-png-depth: Color depth of sprites in the PNG format, optional, default: AUTO.

      1. AUTO: PNG color depth will be chosen automatically. If the sprite image does not contain partial transparencies (alpha channel) and has less than 256 colors, PNG8 will be used. Otherwise, the sprite will be saved in PNG24.
      2. DIRECT: PNG sprites will always be saved in the PNG24 format.
      3. INDEXED: PNG sprites will always be saved in the PNG8 format. If the sprite image contains partial transparencies (alpha channel) or has more than 255 colors, image quality loss may occur and appropriate warnings will be issued. See also the sprite-matte-color property.
    • --sprite-png-ie6: Enables generation of IE6-friendly sprite images, optional, default: disabled.

      If sprite-png-ie6 is specified, for each PNG sprite image with partial transparencies (alpha channel) or more than 255 colors and any transparencies, SmartSprites will generate a corresponding color-reduced PNG8 file for IE6. An extra IE6-only CSS rule will be added to the generated CSS file to ensure that IE6 (and only IE6) uses the color-reduced version:

      #web { width: 17px; height: 17px; background-repeat: no-repeat; background-image: url('../img/mysprite.png'); -background-image: url('../img/mysprite-ie6.png'); background-position: left -0px; }

      See also the sprite-matte-color property.

    • --css-file-encoding: The encoding to assume for input and output CSS files, default: UTF-8. For the list of allowed values, please see the list of encodings supported in Java.
    • --css-file-suffix: Suffix to be appended to the processed CSS file name, optional, default: -sprite.
  7. Integrate SmartSprites with your build scripts. SmartSprites comes with an Ant that performs sprite processing and has exactly the same options as the command line invocation. For an example invocation of the task, please take a look at the build.xml script, whose process task reads parameters from smartsprites.properties and generates sprites. Please note that, contrary to the command line interface, the Ant task resolves all relative paths against the directory in which the build.xml script is located.

Maven plugin

A SmartSprites Maven plugin is available as part of the Jangaroo project. If your project uses Maven, you can easily integrate SmartSprites processing as part of your builds.

Eclipse plugin

To invoke SmartSprites directly from your Eclipse IDE:

  1. Install the Eclipse SmartSprites plugin from: http://update.bitexpert.de/eclipse/3.5
  2. Right-click your CSS file in Project Explorer and choose External Tools > Generate Spritemap to generate sprites.

The plugin was developed by bitExpert AG. Source code of the plugin: https://github.com/bitExpert/eclipse-smartsprites.

Frequently Asked Questions

  1. After conversion to sprites, my design doesn't resemble the original at all. What's wrong?. This may happen :-) First of all, check for SmartSprites warning messages, these indicate that some of the directives have been ignored due to syntactic or semantic errors. Before further investigation, make sure you don't get any warnings.

    Secondly, make sure each SmartSprites directive fits entirely in one line, including the */ sequence closing the comment. Otherwise, you may get unpredictable results.

    Thirdly, as shown in the previous section, SmartSprites for the time being doesn't remove the original background-position properties, but appends its own ones below to shadow them. Your design may break if you have background-position or background-image properties appearing below the line with SmartSprite's sprite reference directive. SmartSprites outputs a warning in such cases. If this happens, move the overriding properties before the sprite reference directive in your original CSS file and run SmartSprites again.

    Finally, you may want to check some SmartSprites tips on Josh's Blog and the excellent CSS sprites starter notes posted by a SmartSprites user on the discussion group.

  2. Other images from the sprite "show through" at places. Why?. This can happen when the box you applied a sprited image to is larger than the sprited image itself. In this situation, other images in the sprite that are below or to the right of it will also be visible.

    To fix this you can size the box to make its dimensions equal to the dimensions of the image. If this is impossible, use sprite margins (e.g. sprite-margin-bottom) to create some empty space around the image in the sprite, so that the other images below it (or right of it) don't show through.

  3. Repeating images in sprites doesn't work. Is it a bug?. Remember that images repeated horizontally (background-repeat: repeat-x) must be added to a vertically laid out sprite (sprite-layout: vertical), and images repeated vertically (background-repeat: repeat-y) must be in a horizontally laid out sprite (sprite-layout: horizontal). There is no way they can work otherwise, hence two sprite image layouts in SmartSprites.
  4. Is there any bigger example of using SmartsSprites I can take a look at? Yes, look in the test/ real-world-example directory of the distribution. This is the original design I was working on when I came up with the idea of SmartSprites.
  5. Are there any tutorials about SmartSprites? Yes, you can find them in the tutorials section.
  6. I've found a bug, how can I report it? Please use our issue tracker.
  7. Do you plan any new features for SmartSprites? Yes, please see our road map for more information.

Version history

v0.2.10, released: June 2013

  • Sprite-alignment should support center option (SMARTSPRITES-36, 3 votes, patch contributed by Artur)

v0.2.9, released: April 2013

v0.2.8, released: February 2011, took about 10 hours of work

  • Possibility to use MD5 hash or time stamp anywhere in sprite image name and path (SMARTSPRITES-41, 3 votes)
  • Releasing SmartSprites binaries into Maven central repository, switching to Maven-based build process (SMARTSPRITES-79)
  • Bugfix: SMARTSPRITES-78

v0.2.7, released: January 2011, took about 3 hours of work

v0.2.6, released: December 2009, took 4 hours of work

v0.2.5, released: December 2009, took 3 hours of work

v0.2.4, released: September 2009, took 28 hours of work

v0.2.3, released: April 2009

v0.2.2, released: April 2009

v0.2.1, released: October 2008

  • Ant not needed anymore to run SmartSprites
  • partial support for the !important modifier in background-image declarations, see SMARTSPRITES-23 for a more in-depth discussion.

v0.2, released: August 2008

  • full support for transparency in GIF, PNG8, PNG24
  • simple color quantization algorithm for GIF and PNG8
  • document-root-relative image paths support
  • arbitrary output directory support
  • SmartSprites Ant task

v0.1, released: February 2008

  • incubation release

Source code

The source code is available on GitHub: https://github.com/carrotsearch/smartsprites The code is continuously built and tested on SmartSprites build server, see below for build artifacts.

Maven dependency

To use SmartSprites in your Java software, add the following dependency to your pom.xml:

<dependency> <groupId>com.carrotsearch</groupId> <artifactId>smartsprites</artifactId> <version>0.2.9</version> </dependency>

Snapshot releases are available from Sonatype's public Maven repositories:

<repositories> <repository> <id>sonatype-nexus-public</id> <name>SonaType public snapshots and releases repository</name> <url>https://oss.sonatype.org/content/groups/public</url> <releases> <!-- set to true if you wish to fetch releases from this repo too. --> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories>

PHP version

For a PHP port of SmartSprites, please check here. You may also want to check Web Optimizer, which supports fully automatic generation of CSS sprites.

Contributors

  • Navtej Sadhal of Redfin: feature ideas and initial code for GIF / PNG8 transparency support

SmartSprites-powered sites

If you would like to list your SmartSprites-powered site here, please let me know on the SmartSprites discussion group.

Tutorials

Support

If you have specific questions, problems or feature ideas for SmartSprites, please visit the SmartSprites CSS Sprite Generator Users and Developers group.