0

I'm embedding an SVG inline with this code:

<div id="svgInlineDiv" style='background-color:white'></div>

<script>
    document.addEventListener("onload",inlineSVG(),false);
    function inlineSVG()
    {
        var SVGFile="img/office_lights.svg";
        var loadXML = new XMLHttpRequest;
        function handler(){
            if(loadXML.readyState == 4 && loadXML.status == 200)
                svgInlineDiv.innerHTML=loadXML.responseText
        }
        if (loadXML != null){
            loadXML.open("GET", SVGFile, true);
            loadXML.onreadystatechange = handler;
            loadXML.send();
        }
    }
</script>

The SVG header looks like this:

<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   id="svg9948"
   version="1.1"
   inkscape:version="0.48.5 r10040"
   sodipodi:docname="office_lights_source.svg"
   viewBox="0 0 1229.4684 1144.845"
   width="100%"
   height="100%">

This image scales only to the width of the browser windows, but not its height.

The picture is roughly square. When I resize the browser window to be higher than it is wide, it is displayed nicely at full width. But when I resize the browser window to be wider than it is high (as one usually does on a widescreen monitor), the picture still shows at full width, forcing me to scroll down to see the lower part.

I've tried playing around with width and height in the CSS as well as the SVG, but to no avail.

EDIT:

Solved by adding height: 100vh to the divs style.
Thanks, Paul LeBeau.

Kirby
  • 303
  • 2
  • 16

1 Answers1

2

Does your <div> have any styling? If not, it will have a width of 100% and a height that matches the height of it's children. In this case that will be the height of the SVG.

The SVG width is being scaled to 100% of the <div> width, which is 100% of the page width.

The height of the SVG is being calculated so that the SVG's aspect ratio (as described by the viewBox) is maintained. So, for example, if your page width is 1024px, the height of the SVG, and hence the <div>, will be:

1024 * (1144.845 / 1229.4684) = 953.53

If you want to restrict the SVG and div to the height of the screen/page, then you will need to use one of the various methods for doing that. For example

Make div 100% height of browser window

Then the SVG will scale to the height of the div. How exactly it gets scaled within the div will depend on the value of the SVG's preserveAspectRatio attribute. You can read about how this attribute works here:

http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute

Community
  • 1
  • 1
Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181