html - 如何在 IE(和其他浏览器)中保留内联 SVG 的纵横比?

标签 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>

SVG 应该是一个红色方 block (其中绘制了一个蓝色方 block ),它根据其父 div 标签缩小,同时保持其纵横比。上面的示例在 Firefox、Chrome(适用于桌面和 Android)、Safari 和 Edge 中运行良好。它呈现一个 80x80 像素的红色方 block :

Correctly displayed in Firefox, Chrome, Safari, Edge

只有 Internet Explorer 10 和 11 将 SVG 垂直拉伸(stretch)到其预期高度的两倍左右,即 80x160 像素:

Incorrectly displayed in IE 10 and 11

如果我删除/注释样式表中的“高度:自动”语句,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 方法似乎遵循不同的假设。

这个问题是以下旧问题的变体,但并不完全相同:

以下要点很有趣但也没有帮助:

有一种称为“填充 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/

相关文章:

jquery - 我如何获取在 iPad 和移动网站上使用 RWD 图像 map 的代码?

javascript - 为什么这些链接在 IE7 中不起作用?

javascript - 发生异常时,应用程序停止响应自定义错误页面

html - 负边距在 IE9 中不起作用

html - 如何自动将 CSS 模拟的表格单元格拆分为多行?

html - 如何使用垂直对齐: middle

php - 使用php从mysql获取html数据中的下拉列表

html - Div 具有相同的类,切换类

javascript - Angular 固定表头故障

javascript - 在 IE Edge 中的 tinyMCE 编辑器上输入内容时出现严重滞后