How do I center an SVG in a div? – Dev

The best answers to the question “How do I center an SVG in a div?” in the category Dev.


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. Doesn’t work, it just acts as if the left margin is 0 (default).

Anyone know my error?


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


SVG is inline by default. Add display: block to it and then margin: auto will work as expected.


None of these answers worked for me. This is how I did it.

position: relative;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);


Having read above that svg is inline by default, I just added the following to the div:

<div style="text-align:center;">

and it did the trick for me.

Purists may not like it (it’s an image, not text) but in my opinion HTML and CSS screwed up over centring, so I think it’s justified.