I have an SVG that I am trying to center in a div. The div has a width or 900px. The SVG has a width of 400px. The SVG has its margin-left and margin-right set to auto. Does
Above answers did not work for me.
Adding the attribute preserveAspectRatio="xMidYMin"
to the <svg>
tag did the trick though. The viewBox
attribute needs to be specified for this to work as well.
Source: Mozilla developer network
I had to use
display: inline-block;
Flexbox is another approach: add
.container {
display: flex;
justify-content: center;
}
And add the .container
class to the div which contains your svg.
Put this two lines in style.css
In your specified div
class.
display: block;
margin: auto;
and then try to run it, you will be able to see that .svg aligned in the center.
For me, the fix was to add margin: 0 auto;
onto the element containing the <svg>
.
Like this:
<div style="margin: 0 auto">
<svg ...</svg>
</div>
Answers above look incomplete as they are talking from css point of view only.
positioning of svg within viewport is affected by two svg attributes
Follow this link from codepen for detailed description
<svg viewBox="70 160 800 190" preserveAspectRatio="xMaxYMax meet">