【问题标题】:Using preserveAspectRatio for external svg对外部 svg 使用 preserveAspectRatio
【发布时间】:2021-08-13 00:35:15
【问题描述】:

#c{
    height: 160px;
    width: 250px;
    background-color: orange;
}

img{
    width: 100%;
    height: 100%;
}
<div id="c">
    <img src="https://restcountries.eu/data/caf.svg" alt="" preserveAspectRatio="none">
</div>

在上面的 sn-p 中,我希望我的图像在不切割的情况下拉伸容器的尺寸。我不介意图像是否会丢失其纵横比。

如果我使用 png 图像而不是 svg,图像会根据我的需要进行拉伸。但是在使用 svg 时,图像会保留其纵横比。

我发现如果我有 svg,我可以使用 preserveAspectRatio 如下 -

.c{
    height: 160px;
    width: 250px;
    background-color: orange;
}

svg{
    width: 100%;
    height: 100%;
}
Preserving aspect ratio - 
<div class="c">
  <svg xmlns="http://www.w3.org/2000/svg" width="450" height="300" viewBox="0 0 1200 800">
    <rect height="200" width="1200" y="0" x="0" fill="#003082"/>
    <rect height="200" width="1200" y="200" x="0" fill="#FFF"/>
    <rect height="200" width="1200" y="400" x="0" fill="#289728"/>
    <rect height="200" width="1200" y="600" x="0" fill="#FFCE00"/>
    <rect height="800" width="200" y="0" x="500" fill="#D21034"/>
    <polygon fill="#FFCE00" points="0,-1,0.22451,-0.30902,0.95106,-0.30902,0.36327,0.11803,0.58779,0.80902,0,0.38197,-0.58779,0.80902,-0.36327,0.11803,-0.95106,-0.30902,-0.22451,-0.30902" transform="translate(200,108.59425) scale(90)"/>
  </svg>
</div>
<br>
Not preserving aspect ratio (What I want) - 
<div class="c">
  <svg xmlns="http://www.w3.org/2000/svg" width="450" height="300" viewBox="0 0 1200 800" preserveAspectRatio="none">
    <rect height="200" width="1200" y="0" x="0" fill="#003082"/>
    <rect height="200" width="1200" y="200" x="0" fill="#FFF"/>
    <rect height="200" width="1200" y="400" x="0" fill="#289728"/>
    <rect height="200" width="1200" y="600" x="0" fill="#FFCE00"/>
    <rect height="800" width="200" y="0" x="500" fill="#D21034"/>
    <polygon fill="#FFCE00" points="0,-1,0.22451,-0.30902,0.95106,-0.30902,0.36327,0.11803,0.58779,0.80902,0,0.38197,-0.58779,0.80902,-0.36327,0.11803,-0.95106,-0.30902,-0.22451,-0.30902" transform="translate(200,108.59425) scale(90)"/>
  </svg>
</div>

但由于我是从外部站点获取 svg,我无法更改 svg 标记。

有解决这个问题的办法吗?

【问题讨论】:

标签: html css image svg


【解决方案1】:

您可以使用 SVG fragment identifier 来覆盖 preserveAspectRatio 的值,例如

#c{
    height: 160px;
    width: 250px;
    background-color: orange;
}

img{
    width: 100%;
    height: 100%;
}
<div id="c">
    <img src="https://restcountries.eu/data/caf.svg#svgView(preserveAspectRatio(none))">
</div>

【讨论】:

    猜你喜欢
    • 2013-01-15
    • 1970-01-01
    • 2017-05-20
    • 2018-11-20
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    相关资源
    最近更新 更多