Actually, if svg is set to viewBox
, then it is scaled, adjusting its size to the container. But I want it to scale only along the horizontal axis, and change its height along the vertical axis without internal scaling.
In the snippet, the same svg markup is placed in divs of different sizes. In the first section, the display is done only with the help of styles, and in the second attribute, the viewBox
modified by the script to show what result I want to get.
I draw attention to the fact that the height of the green rectangle coincides with the width of the blue ones, i.e. stretching without preserving the proportions does not fit.
var divs = document.querySelectorAll(".expected div"); for (var q=0; q<divs.length; ++q) { debugger var d = divs[q]; var svg = d.querySelector("svg"); svg.setAttribute("viewBox", "0 0 10 " + 10 * d.clientHeight / d.clientWidth); }
svg { display: block; width: 100%; height: 100%; } div { display: inline-block; vertical-align: middle; border: 1px dotted red; } section + section { margin-top: 1em; } .a { width: 12em; height: 12em; } .b { width: 4em; height: 8em; } .c { width: 8em; height: 4em; }
<section> <div class="a"> <svg viewBox="0 0 10 10"> <rect x="0" y="50%" width="100%" height="50%" fill="silver" /> <rect x="0" y="0" width="1" height="100%" fill="blue" /> <rect x="9" y="0" width="1" height="100%" fill="blue" /> <rect x="0" y="0" width="10" height="1" fill="green" /> </svg> </div> <div class="b"> <svg viewBox="0 0 10 10"> <rect x="0" y="50%" width="100%" height="50%" fill="silver" /> <rect x="0" y="0" width="1" height="100%" fill="blue" /> <rect x="9" y="0" width="1" height="100%" fill="blue" /> <rect x="0" y="0" width="10" height="1" fill="green" /> </svg> </div> <div class="c"> <svg viewBox="0 0 10 10"> <rect x="0" y="50%" width="100%" height="50%" fill="silver" /> <rect x="0" y="0" width="1" height="100%" fill="blue" /> <rect x="9" y="0" width="1" height="100%" fill="blue" /> <rect x="0" y="0" width="10" height="1" fill="green" /> </svg> </div> </section> <section class="expected"> <div class="a"> <svg viewBox="0 0 10 10"> <rect x="0" y="50%" width="100%" height="50%" fill="silver" /> <rect x="0" y="0" width="1" height="100%" fill="blue" /> <rect x="9" y="0" width="1" height="100%" fill="blue" /> <rect x="0" y="0" width="10" height="1" fill="green" /> </svg> </div> <div class="b"> <svg viewBox="0 0 10 10"> <rect x="0" y="50%" width="100%" height="50%" fill="silver" /> <rect x="0" y="0" width="1" height="100%" fill="blue" /> <rect x="9" y="0" width="1" height="100%" fill="blue" /> <rect x="0" y="0" width="10" height="1" fill="green" /> </svg> </div> <div class="c"> <svg viewBox="0 0 10 10"> <rect x="0" y="50%" width="100%" height="50%" fill="silver" /> <rect x="0" y="0" width="1" height="100%" fill="blue" /> <rect x="9" y="0" width="1" height="100%" fill="blue" /> <rect x="0" y="0" width="10" height="1" fill="green" /> </svg> </div> </section>