Search code examples
pythoncsssvgsvgwrite

Scale and center any svg element full-viewport


My appologies for being the nth person to ask this question. I've snooped around a bunch and haven't cracked it yet.

I would like to be able to scale "any" svg to the full size of the viewport, centered.

For example, consider the following svg element:

    <svg baseProfile="full" height="100%" version="1.1" width="100%"
     xmlns="http://www.w3.org/2000/svg"
     xmlns:ev="http://www.w3.org/2001/xml-events"
     xmlns:xlink="http://www.w3.org/1999/xlink"><defs />
      <polygon fill="blue" points="0,0 10,0 10,10 0,10" />
    </svg>

I would just like to center and up-scale that until it fills the entire browser's viewport. The end result should be a big blue square. Since most displays are wider than they are high, it should be centered and vertically filling the browser...you know, like 9 inches, not 2mm ;-)

Ideally I'd like to also be able to have negative coordinates and have all that "just handled" (eg: center! maximize! thnx!)

I've tried a combination of CSS techniques. None of the method's I've "googled" seem to work.

I feel like the "points" are pixels and therefore "full screen" still means 10x10 pixels. Maybe that's the wrong interpretation.

An aside that may or may not matter: I'm using the Python svgwrite package, which has its own set of ways to scale, translate, rotate... But none of these seem to work for me either.


Solution

  • You have to add a viewBox or you won't be able to scale it.

    Including an ‘svg’ element inside SVG content creates a new SVG viewport into which all contained graphics are drawn; this implicitly establishes both a new viewport coordinate system and a new user coordinate system. Additionally, there is a new meaning for percentage units therein, because a new SVG viewport has been established.

    https://www.w3.org/TR/SVG2/coords.html#EstablishingANewSVGViewport

    svg {
      position: absolute;
      width: 100%;
      height: 100%;
    }
    <svg baseProfile="full" version="1.1" viewBox="0 0 10 10"
         xmlns="http://www.w3.org/2000/svg"
         xmlns:ev="http://www.w3.org/2001/xml-events"
         xmlns:xlink="http://www.w3.org/1999/xlink"><defs />
          <polygon fill="blue" points="0,0 10,0 10,10 0,10" />
        </svg>