Advertisement


Is there any concept of size in an SVG?


Question

I was wondering about SVG files. I know it's a collection of vectors defined by path tags in XML, thus why does it have a width and height in pixels in the svg tag and what if we removed those dimensions?

2016/05/24
1
11
5/24/2016 1:25:00 PM

Accepted Answer

Width and height are only relevant when viewBox is set. Without that attribute you can safely delete width and height. It'll always display at the scale it was drawn at. If a <rect> was set 10px wide 20px high it'll display at that scale 10x20 with or without width or hight when no viewBox is set.

If a viewBox attribute is set you can use the width and height to adjust the original scale up or down.

Without width and height but viewBox set, this will allow the svg to scale infinitely, which may or may not be desired behaviour. In a responsive HTML page this is often desired. It'll scale up or down to fit the bounding container.

These are the same

<svg width="240" height="240" xmlns="http://www.w3.org/2000/svg">
<svg xmlns="http://www.w3.org/2000/svg">

This doubles the original scale.

<svg viewBox="0 0 120 120" width="240" height="240" 
xmlns="http://www.w3.org/2000/svg">

This allows infinite scaling

<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg">
2016/05/24
14
5/24/2016 12:33:00 PM