html - 缩放 div 内的 svg

标签 html css svg

我想把一个 svg 放在 .containerthe following 创建的 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

提前致谢!

最佳答案

我想我明白了。我只是在 .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 作为 ali gajani suggested

关于html - 缩放 div 内的 svg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18253449/

相关文章:

html - 移动 View 错位

html - 对齐容器 div

javascript - 如何根据 Geo ip 数组显示或隐藏元素

html - 如何在 html 和 css 中复制这个@media 屏幕效果?

javascript - 使用 Snap.svg 第二次单击执行某些操作

javascript - 如何使用 D3.js 在 SVG 圆周围绘制 0,45,90,135,180 度等的矩形

javascript - 使用 jquery 将字符串拆分为特定字符处的换行符

javascript - 我怎样才能让我的 JavaScript(如果它是正确的)在倒计时后执行?

android - 手机不想从 Android 浏览器拍照

CSS 多边形阴影