【问题标题】:Resize an SVG to 100% of its parent width and keep its aspect ratio将 SVG 调整为其父宽度的 100% 并保持其纵横比
【发布时间】:2015-01-28 13:51:24
【问题描述】:

我想要一个 SVG 图像,其宽度与父 div 相同,高度应为其宽度的 14%。

此代码在 Firefox 中有效,但在 Chrome 中无效:

<svg 
    xml:space="preserve"
    preserveAspectRatio="xMinYMin meet"
    height="100%" width="100%"
    viewBox="-1 -10 242 33">
    ...
</svg>

在 Chrome 中,纵横比为 1,因此 svg 内容位于正方形的顶部,其下方有很多空白。 我需要将 svg 文件内联,所以我不能使用 img 标记。

【问题讨论】:

  • This has been answered already. 只需从&lt;svg&gt; 标记中删除height="100%" width="100%"
  • 这使得 svg 完全消失。
  • 那你可能还没有给父容器分配宽度。
  • 父级是col-md-12 bootstrap calss,宽度为 100%。

标签: css svg


【解决方案1】:

如果您从 SVG 中删除 heightwidth 属性但保留 viewBox,则它将与其父容器的大小成比例地缩放。例如,以下标记在不同宽度的 &lt;div&gt; 容器中生成三个 SVG 图像。在每种情况下,SVG 都会放大到其父容器的宽度。

这在 Chrome 中对我来说很好用。

<div style="width:200px; height:100px; background-color:#f00; margin-bottom:10px;">
  <svg viewBox="0 0 70 10">
    <rect x="1" y="1" width="68" height="8" fill="#ff0" stroke="none" />
    <text x="35" y="7" font-size="6" text-anchor="middle">&lt;SVG&gt; width=200px</text
  </svg>
</div>
<div style="width:300px; height:100px; background-color:#f00; margin-bottom:10px;">
  <svg viewBox="0 0 70 10">
    <rect x="1" y="1" width="68" height="8" fill="#ff0" stroke="none" />
    <text x="35" y="7" font-size="6" text-anchor="middle">&lt;SVG&gt; width=300px</text
  </svg>
</div>
<div style="width:400px; height:100px; background-color:#f00; margin-bottom:10px;">
  <svg viewBox="0 0 70 10">
    <rect x="1" y="1" width="68" height="8" fill="#ff0" stroke="none" />
    <text x="35" y="7" font-size="6" text-anchor="middle">&lt;SVG&gt; width=400px</text
  </svg>
</div>

【讨论】:

  • Here is an example that uses your code。它适用于 FF,但不适用于 Chrome。
  • @Toast 嗯,这对我来说绝对没问题。我认为您需要做的是:(1)创建导致此问题的标记的minimal, complete and verifiable example,(2)将此标记粘贴到您的问题中,而不是链接到场外网页,以及(3 ) 截取您在 Chrome 中看到的预期行为和错误行为的屏幕截图,并将其插入您的问题中。
  • 如何将引导程序所需的文件放入我的问题中?如果我不提供它们,则代码无法运行...
  • @Toast 你不能直接链接进去吗?为什么会出现这个问题?
  • 我应该从哪里链接它们?这是一个问题,因为示例要么不完整,要么包含引导程序的所有 css 代码。
猜你喜欢
  • 2018-06-21
  • 2017-11-16
  • 1970-01-01
  • 2014-04-17
  • 2018-10-10
  • 2011-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多