将preserveAspectRatio 用于外部svg

Pra*_*xit 2 html css svg image

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

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

在上面的片段中,我希望我的图像在不切割的情况下拉伸容器的尺寸。我不介意图像是否失去纵横比。

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

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

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

svg{
    width: 100%;
    height: 100%;
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)

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

这个问题有什么解决办法吗?

Rob*_*son 7

您可以使用SVG 片段标识符来覆盖 preserveAspectRatio 的值,例如

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

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