一个可缩放的div中嵌入SVG

5
我想把一个SVG放在使用以下代码创建的.container div中,使其完全适应.container div的尺寸,同时随着页面大小的调整而缩放。
<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>

对于这个问题,一个长宽比为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>

然而,当我这样做时,会破坏.container div的纵横比。在Chrome中,.container div的高度会扩展到100%,这显然不是我想要的:P
提前感谢!
2个回答

7
我想我明白了。我只需在 .container div 中添加一个绝对定位的 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>

我在SVG上使用了viewbox,如 阿里·加贾尼 建议的


4

在我的浏览器中,蓝色的 div 已经变得非常高了。你那边也是这样吗? - mulllhausen
希望可以,以下是編程相關內容的中文翻譯。 - mulllhausen
还不对。我希望SVG填充到蓝色div的原始大小。谢谢尝试 :) - mulllhausen
抱歉,我刚意识到我之前从未明确说明过这一点。我现在已经更新了问题。 - mulllhausen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接