Down with absolute units in sprite icons


    Sprites are a cool way to reduce the number of server requests. You can pack a bunch of icons in one sprite and write offsets for each icon in CSS. However, it is very inconvenient that you need to count all this pixel by pixel. Pixels - means no dynamics. If you use pixels, a piece of sprite will be displayed in a fixed size - regardless of whether it is displayed inside a paragraph, or inside a heading. This is wrong, it seems to me, and uncomfortable. But it looks like I found an interesting way to display dynamic size icons.

    First of all, you need to stop thinking about the sprite as a thing with a width and height, expressed in pixels. The sprite in the image in the header has dimensions of 500 by 100 pixels, but it should be taken as a sprite that has a size of 10x2. In fact, what's the difference how many pixels it has? The main thing is that it contains 10 icons in width and two in height.

    During layout, when describing a sprite, you just need to specify the width and height of the background image in relative units - I will use EM. Since the sprite has a size of 10 by 2, it can be described as follows:

    .icon {
        background-image: url(http://i.imgur.com/DV0Bl7B.png);
        display: inline-block;
        /* Ширина — 10, высота — 2. */
        background-size: 10em 2em;
        /* Размеры иконки 1х1 — снова относительные единицы, а не абсолютные */
        width: 1em;
        height: 1em;
    }
    /* Конкретная иконка. Смещение прописывается опять же в относительных единицах */
    .icon-ok-black {
        background-position: -7em -1em;
    }
    


    Due to the fact that all sizes are indicated in relative units, the icon will automatically adjust to the font size - in the title it will correspond to the font size of the title, in the paragraph to the font size of the paragraph, and so on. You can make one sprite, for example, with the size of each icon at 50 pixels, and these 50 pixels will always scale to 1em in the current context.

    However, keep in mind that when scaling bitmaps, the graphics may blur. Perhaps this method is best suited for vector graphics - SVG, for example. Thanks to BaNru for the valuable comment.

    JSFiddle example: jsfiddle.net/vdfqdfen

    Also popular now: