csslayoutsvgpositioningmargin

How do I center a SVG in a div?


I have a SVG that I am trying to center in a div. The div has a width of 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).

Does Anyone know what's the error?


Solution

  • SVG is inline by default.

    Add display: block to it and then margin: auto will work as expected.

    Or depending on your layout you may want to keep SVG inline and set text-align: center on a parent element instead.

    As another alternative, you can center SVG using flex or grid layouts on the parent element.