Becky
Becky

Reputation: 5585

Scale svg by its parent div

I've got a inline svg inside a DIV. How do I make the svg grow/shrink according to the width of its parent div?

It doesn't work in IE but works in chrome. When I used developer tools in chrome I noticed this:

enter image description here

I've read that setAttribute() method can be used to adjust svg's viewBox?

How can I fix this to work in IE?

<div class="mainGA mainG">
   <div class ="drgAM">
       <svg viewBox="0 0 210 500"><polygon points="100,10 40,198 190,78 10,78 160,198"
  style="fill:cyan;stroke:yellow;stroke-width:5;fill-rule:nonzero;" /></svg>
   </div>
</div>

Upvotes: 1

Views: 3227

Answers (3)

Dan Mecklenburg
Dan Mecklenburg

Reputation: 41

Something I just came up with this. Add an onload event to the svg img element that scales to the size of the parent div.

var 
    div = document.createElement('div'),
    img = document.createElement('img');

div.style['width'] = '256px';
div.style['height'] = '128px';
img.onload = fitSVGToDiv;
img.style['visibility'] = 'hidden';
img['src'] = svgData;
div.appendChild(img);
document.body.appendChild(div);

and the onload looks something like...

// ADJUST A <DIV><IMG SRC='...SVG'></DIV> ELEMENT SO SVG FILLS
// DIMENSIONS OF DIV THIS IS AN ONLOAD EVENT FOR SVG IMAGES 
// INSIDE A DIV 
function fitSVGToDiv(e) {
    var 
        p = this.parentNode;

    this.style['transform-origin'] = 'top left';
    this.style['transform'] = 'scale(' 
        + (parseInt(p.style['width']) / this.getBoundingClientRect().width) 
        + ',' 
        + (parseInt(p.style['height']) / this.getBoundingClientRect().height) + ')';
    this.style['visibility'] = 'visible';
}

Upvotes: 0

Pavel Gatnar
Pavel Gatnar

Reputation: 4053

for IE you have to set the width and height to 100% explicitly. set it using CSS:

div.drgAM, div.drgAM svg {
    height: 100%;
    width: 100%;
}

Upvotes: 2

Rodrigo Calix
Rodrigo Calix

Reputation: 627

There are many ways to do that:

First, visit: http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php

i know it will help you a lot!

preserveAspectRatio="xMinYMin meet" might help you with inline SVG. Or in this context you could use svg as an embed image.

if you want to create an elastic inline SVG you can do this:

CSS

.my-div{
    width:100px;
    height:75px;
}
.elastic{
    width:100%;
    height:100%;
}

HTML

<div class="my-div">
    <svg class="elastic"  viewbox="0 0 210 500" preserveAspectRatio="none" >
    </svg>
</div>

hope it helps!

Upvotes: 1

Related Questions