How to use SVG Sprite Sheet as CSS background-image while maintaining aspect ratio and scalability

前端 未结 2 714
不思量自难忘°
不思量自难忘° 2020-12-13 14:28

TL;DR: I want to use several icons tiled in an SVG sprite sheet as CSS background-images, which maintain their aspect ratio and automatically scale to fill the parent elemen

相关标签:
2条回答
  • 2020-12-13 15:06

    If your icons have the same size you can do the following:

    1. Pack your icons into sprite horizontally (use svg-sprite if icons are in separate files).
    2. Set background-size: auto 100%; for your target selector.
    3. Set your target elements' width, height or font-size for scale.

    .icon {
        background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="64" height="16" viewBox="0 0 64 16"> <circle fill="blue" cx="8" cy="8" r="8"/> <circle fill="red" cx="24" cy="8" r="8"/> <circle fill="yellow" cx="40" cy="8" r="8"/> <circle fill="green" cx="56" cy="8" r="8"/> </svg>');
        background-repeat: no-repeat;
        background-size: auto 100%;
        display: inline-block;
    }
    .icon.small {
        height: 1em;
        width: 1em;
    }
    .icon.medium {
        height: 2em;
        width: 2em;
    }
    .icon.large {
        height: 4em;
        width: 4em;
    }
    .icon_1 {
        background-position: 0 0;
    }
    .icon_2 {
        background-position: 33.33% 0;
    }
    .icon_3 {
        background-position: 66.67% 0;
    }
    .icon_4 {
        background-position: 100% 0;
    }
    <span class="icon icon_1 small"></span>
    <span class="icon icon_1 medium"></span>
    <span class="icon icon_2 large"></span>

    0 讨论(0)
  • 2020-12-13 15:08

    Basically, I want to know if there's an easier way to define the cells in the spritesheet and simplify the CSS I use to tell each div which icon to display from the spritesheet.

    No, you can't do it easier.

    Try this article

    Then, there's the problem of scaling. With this setup, the SVG scales to the appropriate size to be drawn on-screen, but if I decide to zoom using my browser's zoom, it pixelates. This is not how SVG is supposed to work.

    In Chromium 18 it looks pretty fine - no pixelations at all.

    In my test browsers list (FF3.6 Opera 9.2 IE6) I didn't see what I saw in Chromium

    And about IE9, maybe problem in engine

    0 讨论(0)
提交回复
热议问题