s-m*_*m-e 5 html css internet-explorer svg aspect-ratio
以下代码片段说明了我的问题:
<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>
Run Code Online (Sandbox Code Playgroud)
SVG 应该是一个红色方块(其中绘制了一个蓝色方块),它相对于其父 div 标签按比例缩小,同时保留其纵横比。上面的示例在 Firefox、Chrome(适用于桌面版和 Android)、Safari 和 Edge 中运行良好。它渲染一个 80x80px 的红色正方形:
只有Internet Explorer 10 和 11 会将 SVG 垂直拉伸到其预期高度的两倍左右,即 80x160px:
如果我删除/注释样式表中的“height: auto”语句,SVG 将缩放为 80x100px。然而,这会破坏 Chrome,在这种情况下,它还会将 SVG 缩放到 80x100px。Firefox 和 Edge 似乎能够处理删除此声明的问题。
有趣的是,SVG 中多边形等的纵横比始终保持完美,请检查蓝色方块,而多边形通常绘制在被拉伸的 SVG 的垂直中心。这是“SVG-container”/SVG-tag,它会带来麻烦并消耗比应有的更多的空间。
如何解决这个跨浏览器问题?
我构建了一个小型JSFiddle来演示该问题。
有一个密切相关的问题,题为“ SVGs not需在 IE 中正确缩放 - 有额外的空间”。关键区别在于,我实际上直接在 svg 标签中提供宽度和高度,这是为了实现Android 浏览器兼容性而需要执行的操作。尽管如此,IE还是崩溃了。Paul LeBeau 描述的画布方法似乎遵循不同的假设。
这个问题是以下旧问题的变体,但并不完全相同:
以下要点很有趣,但也没有帮助:
有一种称为“padding 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>
Run Code Online (Sandbox Code Playgroud)
还有一个更新的JSFiddle。
| 归档时间: |
|
| 查看次数: |
2632 次 |
| 最近记录: |