svg在缩放div中

mul*_*sen 5 html css svg

我想.container在使用以下代码创建的div中放置一个svg ,以便它完全适合.containerdiv的尺寸,但在调整大小时仍然与页面大小成比例:

<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>
Run Code Online (Sandbox Code Playgroud)

为了这个问题的目的,长宽比为2:1的矩形svg将用于:

<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>
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时,它会混淆.containerdiv 的纵横比.使用铬,.containerdiv高度扩大到100%,这显然不是我想要的:P

提前致谢!

mul*_*sen 7

我想我明白了.我只是在.containerdiv中放了一个绝对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>
Run Code Online (Sandbox Code Playgroud)

并且我在svg上使用了viewbox, 正如ali gajani 建议的那样


Ali*_*ani 5

我认为您需要使用 viewbox 属性:http : //www.w3.org/TR/SVG/coords.html#ExampleViewBox

检查这个,它现在可以扩展: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>
Run Code Online (Sandbox Code Playgroud)