SVG tag is taking extra space


Question

So I am getting a weird size issue with the SVG element in HTML5. It is taking considerable more space than I suspected. Each small rectangle in the image is a rect element with width and height of "20".

The SVG element should have height and width of 20*10 = 200 but instead has dimensions of 680x508.

You can view the inspected svg element here -> http://i.stack.imgur.com/xrofn.png

The HTML looks something like this:

    <svg>
    <rect x='0' y='0' height='20' width='20' stroke='black' stroke-width=''/>
    <rect x='0' y='20' height='20' width='20' stroke='black' stroke-width=''/>
    <rect x='0' y='40' height='20' width='20' stroke='black' stroke-width=''/>
    ...
    </svg>

It should be noted that I am running node.js and mustache.js.

Edit: Apparently SVG does something when it isn't sure about the width/height. Setting it manually solves the problem.

    <svg height="200" width="200">
1
5
11/3/2012 4:05:49 PM

Accepted Answer

The SVG viewport seems to be determined by the parent element.

http://www.w3.org/TR/SVG/coords.html states that

The SVG user agent negotiates with its parent user agent to determine the viewport into which the SVG user agent can render the document..

You can specify the size of the SVG viewport by using widht and height

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="200" height="200">
    <rect x='0' y='0' height='20' width='20' stroke='black' stroke-width=''/>
    <rect x='0' y='20' height='20' width='20' stroke='black' stroke-width=''/>
    <rect x='0' y='40' height='20' width='20' stroke='black' stroke-width=''/>
    ...
</svg>
6
11/3/2012 4:11:56 PM

The default value for the width and height attributes on the <svg> element is 100%, which means the SVG viewport depends on the container it's in. Typically this is determined by CSS.

You can set the width and height attributes if you want, but it's also possible to use only CSS for this, as in this example.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon