How to Center an SVG in a div

Hongtao Hao / 2021-03-24


I saw this question on Stack Overflow: How to center an SVG in a div.

Spadar Shut suggested using display: block and margin: auto. Other people, like David suggested using <div style="text-align:center;">.

I tried both methods, and they worked.

To sum, You can either add style = "text-align: center;" to the div, or add style= "display: block; margin: auto" to the svg.

<div style="width: 900; text-align: center">
  <svg id="demo" width="500" height="100" 
       style="background-color: skyblue">
    <rect x="200" y="30" width="100" height="70" 
          style="fill: red"></rect>
  </svg>
</div>

or:

<div style="width: 900">
  <svg id="demo" width="500" height="100" 
        style="background-color: skyblue; display: block; margin: auto">
    <rect x="200" y="30" width="100" height="70" style="fill: red"></rect>
  </svg>
</div>

Last modified on 2021-10-24