#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>
In the above snippet, I want my image to stretch the dimensions of the container without cutting. I don't mind if the image loses its aspect ratio.
If I use a png image instead of a svg, the image stretches according to my need. But while using an svg, the image preserves its aspect ratio.
I found that if I have a svg, I can use preserveAspectRatio
as below -
.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>
But since I am fetching the svg from an external site, I cannot alter the svg
tag.
Any solutions to this issue?
You can use an SVG fragment identifier to override the value of preserveAspectRatio e.g.
#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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With