简体   繁体   English

内联SVG的本征比

[英]Intrinsic ratio for an inline SVG

I'm building an inline SVG with JS. 我正在用JS构建内联SVG。 The proportions (aka ratio) of the SVG is dynamic: at any moment it can be changed from JS. SVG的比例(又称比例)是动态的:随时可以从JS更改它。

I would like to make the SVG responsive. 我想使SVG响应。 This is how i would do it with an <img> : 这就是我要使用<img>

img {
  width: 100%;
  height: auto;
}

But this won't work for <svg> . 但这对<svg>不起作用。 Fiddle: http://jsbin.com/vobaq/1/edit?html,css,output 小提琴: http : //jsbin.com/vobaq/1/edit? html,css, output

The goal is to scale the inline SVG element to fit container horizontally without distorting it's proportions. 目标是缩放内联SVG元素以使其水平适应容器而不会扭曲其比例。 CSS should not know current SVG proportions. CSS不应该知道当前的SVG比例。

The solution is to use the viewbox attribute instead of width and height . 解决方案是使用viewbox属性而不是widthheight Then you don't even need CSS width: 100%; height: auto; 然后,您甚至不需要CSS width: 100%; height: auto; width: 100%; height: auto; !

Demo: http://jsbin.com/vobaq/4/edit?html,css,output 演示: http : //jsbin.com/vobaq/4/edit?html,css,output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM