How to make a <svg> element expand or contract to its parent container?

user782860 picture user782860 · Jan 19, 2012 · Viewed 126.9k times · Source

The goal is to have the <svg> element expand to the size of its parent container, in this case a <div>, no matter how big or small that container may be.

The code:

<style>
    svg, #container{
        height: 100%;
        width: 100%;
    }
</style>

<div id="container">
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" >
         <rect x="0" y="0" width="100" height="100" />
    </svg>
</div>

The most common solution to this problem seems to be setting the viewBox attribute on the <svg> element.

viewBox="0 0 widthOfContainer heightOfContainer"

However, this does not seem to work in cases where elements within the <svg> element have predefined widths and/or heights. For example, the <rect> element, in the above code, has its width and height explicitly set.

So the obvious solution is to use % widths and % heights on those elements as well. But does this even have to be done? Especially, since <img src=test.svg > works fine and expands/contracts without any problems with explicitly set <rect> heights and widths.

If elements like <rect>, and other elements like it, have to have their widths and heights defined in percentages, is there a way in Inkscape to set it so that all elements with the <svg> document use percentage widths, heights, etc.. instead of fixed dimensions?

Answer

robertc picture robertc · Jan 19, 2012

The viewBox isn't the height of the container, it's the size of your drawing. Define your viewBox to be 100 units in width, then define your rect to be 10 units. After that, however large you scale the SVG, the rect will be 10% the width of the image.