SVG viewbox, Image is set to parent element width and not fitted to parent element

904 views Asked by At

I am trying to use the viewbox attribute of SVG to fit the selected area to the screen. The desired effect is that all of the view box area will be shown onscreen, with preserved aspect ratio. Internet explorer and Chrome have the correct behavior with the image area centered both vertically and horizontally.

In opera and firefox the behaviour is not as desired. In wide screens the image is always full width and some of the area is then lost off the bottom

The code I am using is included below with some comments to the problems I have already solved. see the bottom of the page for screenshots

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Svg static view box</title>
<style>
    body, html {
        height: 100%; /* Required to make div fill to screen height, otherwise IE picks smaller image height */
        margin: 0; 
        padding: 0; /* Remove standard behaviour for body margin */
        overflow: hidden;
    }
    div {
        background: red;
        height: 100%; 
    }
</style>
</head>
<body>
<div>
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 2000 1000">
        <rect height="1000" width="2000" y="0" x="0" fill="#afe9c6"/>
        <path d="M40,1000,2000,40" stroke="#00aad4" stroke-width="10" fill="none"/>
        <path d="M40,40,2000,1000" stroke="#00aad4" stroke-width="10" fill="none"/>
        <text font-size="144px" y="550" x="500" >SVG DOCUMENT</text>
    </svg>
</div>
</body>
</html>

Desired effect in chrome Desired effect in chrome

Overflow in Opera Overflow in Opera

1

There are 1 answers

0
Abram On

The viewBox attribute does not affect the layout of the SVG element. All it does is establish coordinates used within the SVG document. See the spec:

http://www.w3.org/TR/SVG11/coords.html#ViewBoxAttribute

Use HTML CSS to give the SVG element a margin or specific width and height. With what you have, there's no specified size for the SVG element, and so you're going to get undefined behavior.