1

Is there any way to set the value of preserveAspectRatio for SVG sprites on a per-instance basis using CSS, HTML, or some other method (besides JavaScript)?

For example (none of these appear to work):

<!-- inline html on <svg> -->
<svg preserveAspectRatio="xMinYMin">
  <use xlink:href="/svg/icon.svg">
</svg>

.

<!-- inline html on <use> -->
<svg>
  <use xlink:href="/svg/icon.svg" preserveAspectRatio="xMinYMin">
</svg>

.

<!-- inline css nested in <svg> -->
<svg>
  <style>svg { preserveAspectRatio: xMinYMin; }</style>
  <use xlink:href="/svg/icon.svg">
</svg>

.

<!-- inline css nested in <use> -->
<svg>
  <use xlink:href="/svg/icon.svg">
    <style>svg { preserveAspectRatio: xMinYMin; }</style>
  </use>
</svg>

.

<!-- head/external css -->
<style>
  .icon,
  .icon svg {
    preserveAspectRatio: xMinYMin;
  }
</style>

<svg class="icon">
  <use xlink:href="/svg/icon.svg">
</svg>
cantera
  • 24,479
  • 25
  • 95
  • 138

1 Answers1

2

In SVG 1.1 you can only use <image> elements to refer to complete files. SVG 2 relaxes this so that <use> elements can point to complete files but I'm not sure any UAs have implemented this.

For image elements you'd do this...

<svg>
  <image width="100" height="100" xlink:href="/svg/icon.svg#svgView(preserveAspectRatio(none slice))">
</svg>

In SVG 1.1 width and height are mandatory for images. The svgView syntax is documented here

Robert Longson
  • 118,664
  • 26
  • 252
  • 242