Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale SVG image to fill browser window?

This seems like it ought to be easy, but I'm just not getting something.

I want to make an HTML page containing a single SVG image that automatically scales to fit the browser window, without any scrolling and while preserving its aspect ratio.

For example, at the moment I have a 1024x768 SVG image; if the browser viewport is 1980x1000 then I want the image to display at 1333x1000 (fill vertically, centred horizontally). If the browser was 800x1000 then I want it to display at 800x600 (fill horizontally, centred vertically).

Currently I have it defined like so:

<body style="height: 100%">
  <div id="content" style="width: 100%; height: 100%">
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1"
         width="100%" height="100%"
         viewBox="0 0 1024 768"
         preserveAspectRatio="xMidYMid meet">
      ...
    </svg>
  </div>
</body>

However this is scaling up to the full width of the browser (for a wide but short window) and producing vertical scrolling, which isn't what I want.

What am I missing?

like image 433
Miral Avatar asked Apr 13 '11 00:04

Miral


People also ask

Can SVG images be scaled?

SVG images can thus be scaled in size without loss of quality, and SVG files can be searched, indexed, scripted, and compressed. The XML text files can be created and edited with text editors or vector graphics editors, and are rendered by the most-used web browsers.

How do I make SVG Scalable?

Once you add a viewBox to your <svg> (and editors like Inkscape and Illustrator will add it by default), you can use that SVG file as an image, or as inline SVG code, and it will scale perfectly to fit within whatever size you give it. However, it still won't scale quite like any other image.

How do I fit an image in SVG?

You could arrange for the viewBox area to be enlarged to fit the wider SVG dimensions (equivalent to HTML's background-size: cover ), by adding preserveAspectRatio="xMidYMid slice" to the SVG.


1 Answers

How about:

html, body { margin:0; padding:0; overflow:hidden }
svg { position:fixed; top:0; bottom:0; left:0; right:0 }

Or:

html, body { margin:0; padding:0; overflow:hidden }
svg { position:fixed; top:0; left:0; height:100%; width:100% }

I have an example on my site using (roughly) this technique, albeit with 5% padding all around, and using position:absolute instead of position:fixed:
http://phrogz.net/svg/svg_in_xhtml5.xhtml

(Using position:fixed prevents a very edge-case scenario of linking to a sub-page anchor on the page, and overflow:hidden can ensure that no scroll bars ever appear (in case you have extra content.)

like image 119
Phrogz Avatar answered Oct 18 '22 22:10

Phrogz