mulllhausen
mulllhausen

Reputation: 4435

svg inside a scaling div

i want to put an svg inside the .container div created with the following code so that it fits exactly to the dimensions of the .container div but still scales with the size of the page as it is resized:

<html>
    <body>
    <style type='text/css'>
.container
{
    position:relative;
    width:50%;/*half the width of the whole page*/
    margin:auto;/*center the whole thing*/
}
.set_height
{
    padding-bottom:50%;/*2:1 aspect ratio*/
    position:relative;
    float:left;
    width:100%;
    height:100%;
}
    </style>
        <div class='container'>
            <div class='set_height' style='background-color:blue;'>
            </div>
        </div>
    </body>
</html>

a rectangular svg with an aspect ratio of 2:1 will do for the purposes of this question:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
    <rect x="0" y="0" width="100" height="50" stroke="black" fill="red" stroke-width="5"/>
</svg>

however when i do this, it messes up the aspect ratio of the .container div. using chrome the .container div height expands out to 100%, which is obviously not what i want :P

thanks in advance!

Upvotes: 5

Views: 22678

Answers (2)

mulllhausen
mulllhausen

Reputation: 4435

I think I got it. I just put an absolute div within the .container div:

.on_top
{
    position:absolute;
    top:0;left:0;bottom:0;right:0;/*expand this div to the size of its parent*/
}
    <div class='set_width'>
        <div class='on_top'>
            <svg viewBox="0 0 100 50" version="1.1" xmlns="http://www.w3.org/2000/svg">
                <rect x="0" y="0" width="100" height="50" stroke="black" fill="red" stroke-width="5"/>
            </svg>
        </div>
        <div class='set_height'></div>
    </div>

and I used viewbox on the svg as ali gajani suggested

Upvotes: 7

Ali Gajani
Ali Gajani

Reputation: 15091

I think you need to use the viewbox attribute: http://www.w3.org/TR/SVG/coords.html#ExampleViewBox

Check this, it scales now: http://jsfiddle.net/NKRPe/60/

 <svg viewBox="0 0 1500 1000" preserveAspectRatio="none" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <rect x="0" y="0" width="100" height="50" stroke="black" fill="red" stroke-width="5"/>
</svg>

Upvotes: 4

Related Questions