是否可以使用 CSS 缩放内联 SVG?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20775448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is is possible to scale inline SVG with CSS?
提问by emersonthis
I want to use CSS styles to control the size of SVG designs. For example...
我想使用 CSS 样式来控制 SVG 设计的大小。例如...
.svg { width:100%; }
When I embed an SVG image from a file it acts just like any other image and works fine:
当我从文件中嵌入 SVG 图像时,它的行为就像任何其他图像一样并且工作正常:
<img src="image.svg" class="svg" />
But when I use inline SVG it DOESN't work:
但是当我使用内联 SVG 时它不起作用:
<svg class="svg">...</svg>
The svg "box" will grow, but the contents stay the same.
svg“盒子”会增长,但内容保持不变。
Is there a way to do this?
有没有办法做到这一点?
回答by Joeytje50
The first and probably best method you could use is just using the viewBox
attribute (this attribute is case sensitive). That will make the contents of the svg tag automatically take up the defined width and height of the svg tag itself, by only showing what's within the defined boundaries. For example:
您可以使用的第一个也是最好的方法就是使用该viewBox
属性(该属性区分大小写)。这将使 svg 标签的内容自动占据 svg 标签本身定义的宽度和高度,只显示定义边界内的内容。例如:
<svg width="82" height="82" viewBox="0 0 102 102">
<rect x="1" y="1" width="100" height="100" stroke="black" stroke-width="2" fill="white"/>
<text fill="black" x="10" y="30">FooBarBaz</text>
</svg>
Alternatively, you could apply a svg transform
to the contents of the SVG tag, which would look like this:
或者,您可以将 svgtransform
应用于 SVG 标记的内容,如下所示:
<svg width="82" height="82">
<g transform="scale(0.8)">
<rect x="1" y="1" width="100" height="100" stroke="black" stroke-width="2" fill="white"/>
<text fill="black" x="10" y="30">FooBarBaz</text>
</g>
</svg>
Finally, you can try using CSS3 transform
to scale the whole svg element. This is the least supported method, but I mention it anyway because you originally asked for a CSS solution. I strongly suggest using one of the above solutions though, if that's possible at all.
最后,您可以尝试使用 CSS3transform
来缩放整个 svg 元素。这是最不受支持的方法,但我还是提到了它,因为您最初要求的是 CSS 解决方案。不过,如果可能的话,我强烈建议使用上述解决方案之一。
<svg width="102" height="102" style="transform:scale(0.8); -webkit-transform:scale(0.8); -moz-transform:scale(0.8); -ms-transform:scale(0.8); -o-transform:scale(0.8);">
<rect x="1" y="1" width="100" height="100" stroke="black" stroke-width="2" fill="white"/>
<text fill="black" x="10" y="30">FooBarBaz</text>
</svg>