CSS Sprites 2.0

    After publishing a series of articles on the use , uselessness and even automation of CSS Sprites , after many days of analysis of the current state of things, I managed to collect some of the most common problems when using CSS Sprites and methods for solving them. The following also discusses the application method for automating the creation of CSS Sprites for an arbitrary project.

    Technology Overview


    CSS Sprites, in fact, is just an expanded use of the technology backgroundlaid down in the CSS1 specification. All that progressive mankind has come up with over the years is the multiple background of the elements (how it will be compatible with the CSS Sprites concept still has to be verified). The main properties that we use to set the background image.
    • background-image- The main "workhorse". It is her future data:URIthat will ultimately defeat CSS Sprites. But this will not happen soon.
    • background-repeat- The second no less important component when using a background image. After all, setting no-repeatthis property, we intentionally emphasize that CSS Sprites is acceptable for gluing images (it is used by default repeat).
    • background-position - "magic wand" for CSS Sprites, which allows you to hide or show certain parts of the background image.


    In addition to the declared properties, there are also several more (for example, background-color), but they are mediocre to sprites.

    So, we can set the source of the image, the rule for its repetition and its initial position. It seems enough?

    Applied Subtleties


    Naturally, considering the set of possible effects when using background images, it is worth noting the following:

    • An object that is completely filled with a background image. Here the main role is played by the final dimensions of the object (of course, if the image is not repeated along all axes at once: in this case it is not possible to use it for CSS Sprites). Quite often, the background under the object may change depending on some conditions (intentional accent or actions by users), but for the logic of creating CSS Sprites this is not essential. Here, three subcases can be distinguished, corresponding to a non-repeating background and repeating along the X or Y axis.
    • The background image does not fill the entire volume provided to it (either the object’s dimensions are not specified, or are specified in relative - em,% - units). Here we need to either attach a repeating image “to the end” of the sprite so that no defects appear on that part of the object that was left without a background image. Or (in the case no-repeat) arrange the images with a “ladder” (this is especially true in the case of a background for list items). It is worth noting that depending on the value of background-positionCSS Sprites here may be both possible and not possible in principle (for example, in the case 100% 100%). There can be distinguished several cases with different background-position, background-repeatand linear block sizes.
    • The image is animated . Since the discussion below will focus on the use of PNG and JPEG images for CSS Sprites, animated images will have to be immediately discarded: support for animated PNG images is now at its most embryonic level in browsers.


    All the described examples can be more clearly structured into the following groups.

    1. background-repeat: no-repeat, background-position: абсолютные числаAnd given the linear absolute dimensions.
    2. background-repeat: no-repeat, background-position: абсолютные числаWhose linear dimensions are not specified or defined in relative units.
    3. background-repeat: repeat-x, the height of the element is set.
    4. background-repeat: repeat-x, Element Height Not Set.
    5. background-repeat: repeat-y, the element width is set.
    6. background-repeat: repeat-y, element width not set.
    7. background-repeat: no-repeat, background-position: 100% 0, Set the element height.
    8. background-repeat: no-repeat, background-position: 0 100%, Set the cell width.
    9. background-repeat: no-repeat, background-position: 100% 0, Element height is not set.
    10. background-repeat: no-repeat, background-position: 0 100%, The cell width is specified.
    11. background-repeat: repeat.
    12. background-repeat: repeat-xor background-repeat: repeat-y, element dimensions are in relative units.
    13. background-repeat: no-repeat, background-position: в относительных единицах.
    14. The image is an animated GIF file.


    Looking at this specification, in general, it becomes clear in which direction to move to automate the creation of CSS Sprites.

    Practical solution


    Next, we will talk about the Auto Sprites tool , which was the basis for the development of Web Optimizer . After the above conclusions, purely technical questions remained: how to encode all this.

    First, we need to parse the entire tree of CSS rules, then select from them related to background images and linear sizes of objects, and then perform the required actions on them. CSS Tidy is ideal for this task , which has been wonderfully tested, tested, and improved after a couple of small bugs.

    Then the fun begins: how do we “glue” the above groups? To do this, use the following algorithm:
    1. repeat-ximages (group 3) are combined together vertically. Along the way, the width of the background images is corrected (reduced to a common denominator). At the very beginning of such a file, no-repeatimages suitable in width are added (group 1). Then in the most of them file is written 1 image from group 4 (more than 1 will still not go anywhere).
    2. Absolutely similar actions are performed with repeat-y.
    3. Further, images from group 7 are combined vertically ( 0 100%means that the background should be pressed to the right edge of the element, respectively, the entire sprite will be “pressed” to its right edge).
    4. Similarly with group 8 - we press everything to the bottom. Naturally, for all groups we take into account the initial one background-position.
    5. We calculate the positioning for the images of group 1 (for this, it’s just fine to sort the images sorted by area: we’ll prepare a matrix into which we are trying to “fit” the next image, if it doesn’t work, then we increase the matrix).
    6. We build a "ladder" from the images of the second group. It’s better to build a ladder at the bottom of the already created sprite from the previous paragraph: then it is easy to find the minimum size of a “hole” between two groups of images in order to move the ladder up (and then, possibly to the left). Of course, finding the most optimal location is a non-trivial task. But it can also be solved in a rather crude approximation, which is described above.
    7. The image from point 3 is attached to the upper right corner of our complex image (the result of steps 5 and 6). Since each such image has a permissible height and all of them are outside the “working” zone of the remaining no-repeatimages, no rudiments will arise.
    8. We do the same with the image from point 4 - we place it in the lower left corner of our sprite.
    9. At the output, we get 3 sprites with all possible cases. On average, the size of such sprites will only slightly exceed (if at all) similar "manual" analogs (including through the use of PNG). Naturally, you can automatically skip through pngcrushor jpegtran. It is also worth considering in which form full-color images will be created: JPEG or PNG (the latter are larger in size, but guarantee no quality loss).


    All the described steps have already been applied in Web Optimizer (a web application for automating client optimization), one of the final versions of the algorithm works for the Auto Sprites tool , and the source text can be found in SVN .

    This logic can be applied at any stage of web development (both during the initial creation of the design and in the post-release site optimization). The library for the automatic creation of sprites is distributed under the MIT license (as I was correctly pointed out by CodeCamp , it allows you to use the product anywhere and anyway , but there must be a link to the source, even if not the entire library is used, but only its essential part).

    Live examples


    All pictures are obtained on a real configuration of well-known CMS.

    CSS Sprites Example (PNG)

    CSS Sprites Example (JPEG)

    PS News about Web Optimizer will now be published on Twitter .

    Also popular now: