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

前端 未结 2 718
不思量自难忘°
不思量自难忘° 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,     ');
        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;
    }
    
    
    

提交回复
热议问题