Home > Mobile >  Can you set the height and width attributes of an SVG somewhere in the sprite sheet?
Can you set the height and width attributes of an SVG somewhere in the sprite sheet?

Time:09-28

I'm trying to use SVGs the cleanest way by using a sprite sheet but something grinds my gear. The SVGs I downloaded come with a width and height attributes like so:

<svg id="icon-ellipsis" width="21" height="5">
  <use href="/icons.svg#icon-ellipsis"></use>
</svg>

What I would like is to have those attributes in the sprite sheet and not the markup because I think it would be cleaner, the markup then only references the icon and doesn't deal with how it should look

It also would be more convenient. If for some reason you want to list all your SVGs in the sprite sheet without having any markup yet (at the beginning of a project for example), well if they don't have those attributes it's not going to look as expected when you are going to call them

So anyway I tried putting them on the <symbol> element like you would with viewBox but it doesn't seem to work:

<svg xmlns="http://www.w3.org/2000/svg">
  <symbol id="icon-ellipsis" width="21" height="5">
    <path d="M2.5 0a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5Zm8 0a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5Zm8 0a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5Z" fill-rule="evenodd" />
  </symbol>
</svg>

Is there a way to do it?

CodePudding user response:

You can use viewBox on the symbol, width and height = 100% on the svg, and finally use width and height on the use element.

 <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%">
      <symbol id="icon-ellipsis" viewBox="0 0 21 5">
        <path d="M2.5 0a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5Zm8 0a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5Zm8 0a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5Z" />
      </symbol>
      <use xlink:href="#icon-ellipsis" x="0" y="0" width="21" height="5" fill="blue" />
      <use xlink:href="#icon-ellipsis" x="0" y="100" width="100" height="25" fill="#eef" />
      <!-- Even uses with different width/height ratio get rendered ok because of viewBox attribute -->
      <use xlink:href="#icon-ellipsis" x="100" y="100" width="200" height="10" fill="#ff0" />
    </svg>

CodePudding user response:

Short answer: no you can't. Not with a sprite sheet.

It doesn't really make sense anyway. If you want to fix the width and height of your SVG symbols to specific pixel values, then why bother using SVG? You might as well just use a PNG spritesheet.

  • Related