Question

I'm encountering a problem with scaling an SVG document. It's included in an HTML document:

<svg class="svg_class">
    <path class="path_class"     
             d="M 403...
             ... 
             ...z"/>
</svg>

I tried to scale it with CSS, as follows:

svg.svg_class {
    height: 100%;
    width: 100%;    
}

… to no avail. I also tried using px units, but that doesn't work either.

I can make it work using transform: scale(0.1);, but is there another way to solve this, e.g. when specifying dimensions in attributes as with img elements?

Was it helpful?

Solution

Use the viewBox attribute on the svg element, it's designed for that purpose. In conjunction with preserveAspectRatio it grants full control over scaling the SVG canvas.

Further reading

References

OTHER TIPS

Look at www.w3.org/TR/SVG/styling.html, section 6.16 User agent style sheet. You apparently need to give height="xxx" in the <svg> tag, or for CSS use attr().

If you want to fill the browser screen fully with your svg...

An SVG Image fills the screen when: The body style="overflow:hidden". It is included in a DIV (style="position:absolute;top:0px;left:0px;"). Sets the SVG width/height to window.innerWidth/innerHeight The svg viewBox attribute is set to the bounding box values of the svg image.

Try this example:

<body style='overflow:hidden;background-color:red'>
    <div id="svgDiv" style='position:absolute;top:0px;left:0px;background-color:lightgreen;'>
        <svg id="mySVG">
            <circle id="myCircle" cx="120" cy="180" r="40" fill="red" stroke="black" stroke-width="2" />
            <rect id="myRect" x="220" y="250" width="60" height="60" fill="blue" stroke="black" stroke-width="2" />
            <ellipse id="myEllipse1" cx="900" cy="1200" rx="150" ry="75" fill="yellow" stroke="black" stroke-width="2" />
            <ellipse id="myEllipse2" cx="1900" cy="90" rx="150" ry="75" fill="yellow" stroke="black" stroke-width="2" />
            <ellipse id="myEllipse3" cx="3900" cy="2200" rx="150" ry="75" fill="yellow" stroke="black" stroke-width="2" />
        </svg>
    </div>

Then fire the function onload:

function sizeFull() {
    var svgW=window.innerWidth
    var svgH=window.innerHeight
    var bb=mySVG.getBBox()
    var bbx=bb.x
    var bby=bb.y
    var bbw=bb.width
    var bbh=bb.height
    mySVG.setAttribute("viewBox",bbx+" "+bby+" "+bbw+" "+bbh )
    mySVG.setAttribute("width",svgW)
    mySVG.setAttribute("height",svgH)
}
document.addEventListener("onload",sizeFull(),false)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top