Open In App

How to make an svg scale with its parent container ?

SVG is the abbreviation for Scalable Vector Graphics. It is an Extensible Markup Language (XML) based vector image format for two-dimensional graphics. It supports interactivity and animation. This means that every attribute and every element present in the SVG file can be animated. SVG image behaviors are defined in XML text files. They can be searched, indexed, scripted, compressed, and can be created or edited using any text editor, as well as using drawing software such as Inkscape. Almost every modern web browser support SVG. 

The reason why it is tricky to scale SVG is that it does not scale like the other image formats. SVG images have a clearly defined aspect ratio: the ratio of width to the height which makes it difficult to scale with the changing parent container. Other images scale easily because the browser determines the height, width, and aspect ratio of the image, and it adjusts everything accordingly. So giving these properties to SVG should be the first step to our requirement. Although setting height and width barely sets an aspect ratio but what we aim for is scaling which is beyond the aspect ratio. A viewbox can serve our purpose rightly. The viewBox is an attribute of the <svg> element which takes four parameters x, y, width, and height. x and y signify the origin of the SVG coordinate system and width and height signify the number of pixels or coordinates that should be scaled to fill the width and height respectively. Let us take a look at the following example:



First approach:

Example:






<!DOCTYPE html>
<html>
  
<body>
    <div class="container" style=
            "width:30%; height: 20%; 
            border:1px dashed black;">
  
        <svg width="100%" height="auto" 
            viewBox="0 0 100 100">
            <rect width="50" height="50" 
                style="fill:rgb(0,170,0);
                    stroke-width:1;
                    stroke:rgb(0,0,0)" />
        </svg>
    </div>
</body>
  
</html>

Output:

Full Screen

Minimized Screen

Second approach: 

Example:




<!DOCTYPE html>
<html>
  
<body>
    <div class="container" style=
        "width:80%; height:80%; 
        border:1px dashed black;">
  
        <img src="E:\method-draw-image.svg" 
            style="width:50%">
    </div>
</body>
  
</html>

Output:

Full Screen

Minimized Screen


Article Tags :