How do I auto-scale <svg> element and content? (D3.js)

Is it possible to scale a svg element (and all content I have accordingly) without cropping? I tried scaling the svg to 100% width and height, but the content is clipping.

svg is generated via d3.js

Html

<svg>
  <circle cx="50" cy="50" r="50" fill="red"></circle>
</svg>

      

CSS

svg {
  width: 100%;
}

      

+3


source to share


1 answer


Oh well, I understand:

<svg width="100" height="100">
  <circle cx="50" cy="50" r="50" fill="red"></circle>
</svg>

      

This means: width = 100px, not 100% . Ditto for the circle attribute, cx = "50" means X coordinate = 50px, not 50%.

What can you do:

Html



<svg class="scaled-svg">
  <circle cx="50%" cy="50%" r="20%" fill="red"></circle>
</svg>

      

CSS

.scaled-svg {
  width: 100%;
  height: auto; /* or 100% but it can break the ratio */
}

      

With this SVG code will be

-1


source







All Articles