Reputation: 363
How can I display an SVG image within an object tag at a different scale than its original scale?
For example, if I have an SVG file saved as example.svg:
<?xml version="1.0" encoding="UTF-8" ?>
<svg xmlns="http://www.w3.org/2000/svg"
version="1.1"
viewBox="0 0 100 100">
<circle cx="50" cy="50" r="50" fill="orange"></circle>
</svg>
and I want to display this in page.html at a different scale:
<!DOCTYPE html>
<html>
<head></head>
<body>
<object type="image/svg+xml" data="/example.svg" width="50" height="50">
</object>
</body>
</html>
It ought to display a version of the svg scaled down to 50x50, but instead it keeps the scale the same and gives the image scrollbars.
However, if I do an inline SVG like the following, it works:
<!DOCTYPE html>
<html>
<head></head>
<body>
<svg xmlns="http://www.w3.org/2000/svg"
version="1.1"
width="50"
height="50"
viewBox="0 0 100 100">
<circle cx="50" cy="50" r="50" fill="orange"></circle>
</svg>
</body>
</html>
I have tried various combinations of this, such as adding width="100" and height="100" into the .svg file, using preserveAspectRatio="xMidYMid meet", adding 'px' to the width and height values, using width and height = "100%" in the svg, and other things, but none of them have worked.
In my situation I can just include the svg inline, but I don't feel like it should be that hard to change the scale of the image. Plus I want the browser to be able to cache the image.
Upvotes: 1
Views: 5069
Reputation: 161
What works for me is the following: I define the "basic" size of the svg with a viewbox and also add the attributes "height=100% width=100%". This means, that the svg will take 100% of the width and height of its parent element. If I put the SVG in an <object>
tag, I simply define the size of the object per css and voila, the SVG automagically adapts its size. In the example, I scale an SVG where the viewbox defines a size 100x100px to 300x300px.
file.svg
<svg viewBox="0 0 100 100" width="100%" height="100%">
<path .... />
</svg>
HTML:
<object type="image/svg+xml" data="your/path/to/file.svg" class="icon"></object>
CSS:
object.icon{
height:auto;
width: 300px;
}
Upvotes: 0
Reputation: 101956
You need to set the width and height attributes of your svg element to 100%. It will then be scaled to the size of the container (the object element). Without that, it will just be displayed at the exact size specified (100 pixels).
<?xml version="1.0" encoding="UTF-8" ?>
<svg xmlns="http://www.w3.org/2000/svg"
version="1.1"
viewBox="0 0 100 100"
width="100%" height="100%">
<circle cx="50" cy="50" r="50" fill="orange"></circle>
</svg>
Upvotes: 3
Reputation: 124269
SVG is case sensitive. If you change viewbox to the correct case of viewBox in example.svg then this displays as you want it to (at least it does on Firefox and Opera I didn't try other UAs).
Upvotes: 2