Rectangle 27 0

javascript SVG with viewBox and width is not scaling height correctly in IE?


.wrap {
  position: relative;
}
img {
  width: 100%;
  height: auto;
}
.viz {
  position: absolute;
  top: 0;
  left: 0;
}
<div class="wrap">
  <img src="img/blank.png" />
  <div class="viz">
    <svg preserveAspectRatio="xMinYMin slice" viewBox="0 0 1000 600"></svg>               
  </div>
</div>

In this case, your image should have natural dimensions of 1000px by 600px and be transparent (or matching the background of your .wrap container). This will appropriate the size of the container the svg sits inside. The absolute position of the .viz element will allow it to sit on top of the image, utilizing it's height so nothing gets cut off.

One workaround that should work in all browsers is to add a blank image to the container your SVG sits inside, which has the same dimensions as your SVG:

Note
Rectangle 27 0

javascript SVG with viewBox and width is not scaling height correctly in IE?


/*
Here we do the hack.
With the math type: percent * height/width
we are adjust the total height of an element who is depend in width using the padding-bottom.
You can put an inline padding-bottom if you want in html.
*/

$(function() {
  $('svg').each(function() {
    var svg = $(this);
    var text = svg.find('text');
    var bbox = text.get(0).getBBox();
    //the hack
    var calcString = "calc(100% * " + bbox.height/bbox.width + ")";
    svg.css("padding-bottom",calcString);

    svg.get(0).setAttribute('viewBox',
                           [bbox.x,
                            bbox.y,
                            bbox.width,
                            bbox.height].join(' '));
  });
});
<!--
xMidYMin: Align the midpoint X value of the element's viewBox with the midpoint X value of the viewport.
slice : the entire viewport is covered by the viewBox and the viewBox is scaled down as much as possible,
height: if you dont set >= 1px some browsers will not render anything.
-->
<div>
    <svg viewBox="0 0 100 10" preserveAspectRatio="xMidYMin slice"
         width="100%" style="height: 1px;overflow: visible;
         /*without js:padding-bottom:55%*/"><text>hello</text>
  </svg>
    <svg viewBox="0 0 100 10" preserveAspectRatio="xMidYMin slice"
         width="100%" style="height: 1px;overflow: visible;"><text>Age</text>
  </svg>
</div>

Some browsers(IE and safari) will be use a default size to SVG if you don't put a certain height and width. That what is happening here. You are right, the "intrinsic aspect ration" is requiring another Dom and css and will be nice if we can overcame this.

There is a solution to this, you can calculate and put the right height to padding-bottom and this will give the right "unknown height" you want. You can see a full solution here: http://codepen.io/tomkarachristos/pen/GZPbgZ

and javascript:

Note