以下代码片段说明了我的问题:
<style>
div {
background-color: #00FF00;
width: 80px;
}
svg {
background-color: #FF0000;
vertical-align: top;
width: 100%;
height: auto; // PROBLEM
}
rect { fill: #0000FF; }
</style>
<div>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 100"
shape-rendering="geometricPrecision"
text-rendering="geometricPrecision"
image-rendering="optimizeQuality"
fill-rule="evenodd"
clip-rule="evenodd"
preserveAspectRatio="xMidYMid meet"
width="100"
height="100"
>
<rect width="90" height="90" x="5" y="5" />
</svg>
</div>
SVG 应该是一个红色方 block (其中绘制了一个蓝色方 block ),它根据其父 div 标签缩小,同时保持其纵横比。上面的示例在 Firefox、Chrome(适用于桌面和 Android)、Safari 和 Edge 中运行良好。它呈现一个 80x80 像素的红色方 block :
只有 Internet Explorer 10 和 11 将 SVG 垂直拉伸(stretch)到其预期高度的两倍左右,即 80x160 像素:
如果我删除/注释样式表中的“高度:自动”语句,SVG 将缩放为 80x100 像素。然而,这会破坏 Chrome,在这种情况下,它还会将 SVG 缩放到 80x100px。 Firefox 和 Edge 似乎能够处理删除此声明。
有趣的是,SVG 中多边形等的纵横比始终保持完美,请检查蓝色方 block ,而多边形通常绘制在被拉伸(stretch)的 SVG 的垂直中心。是“SVG-container”/SVG-tag,它会引起麻烦并占用更多空间。
我该如何解决这个跨浏览器问题?
我建了一个小 JSFiddle 来证明这个问题。
有一个密切相关的问题,标题为“SVGs not scaling properly in IE - has extra space”。 关键区别在于我实际上直接在 svg 标签中提供宽度和高度,我需要这样做 for Android browser compatibility 强>。尽管如此,IE还是坏了。 Paul LeBeau 描述的 Canvas 方法似乎遵循不同的假设。
这个问题是以下旧问题的变体,但并不完全相同:
- Cross browser SVG preserveAspectRatio
- SVG in img element proportions not respected in ie9
- SVG scaling in Internet Explorer
以下要点很有趣但也没有帮助:
- Fix SVG in tags not scaling in IE9, IE10, IE11 (这实际上是关于 img-tags 中的 SVG,删除 SVG 标签中的宽度和高度参数对我不起作用)
有一种称为“填充 hack”的方法,在此处进行了描述:
最佳答案
此答案仅供引用 - 我仍在寻找更好、更简单(也更简单)的方法来做到这一点。
好的,按照“padding hack”的思路,以下内容似乎适用于各种浏览器:
<style>
div#outer {
background-color: #00FF00;
width: 80px;
}
div#container {
position: relative;
height: 0;
width: 100%;
padding: 0;
padding-bottom: 100%; /* 100% * height/width */
}
svg {
background-color: #FF0000;
position: absolute;
height: 100%;
width: 100%;
left: 0;
top: 0;
}
rect { fill: #0000FF; }
</style>
<div id="outer">
<div id="container">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 100"
shape-rendering="geometricPrecision"
text-rendering="geometricPrecision"
image-rendering="optimizeQuality"
fill-rule="evenodd"
clip-rule="evenodd"
preserveAspectRatio="xMidYMid meet"
width="100"
height="100"
>
<rect width="90" height="90" x="5" y="5" />
</svg>
</div>
</div>
还有更新的JSFiddle .
关于html - 如何在 IE(和其他浏览器)中保留内联 SVG 的纵横比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43870420/