css - How do I center an SVG in a div?

ID : 10101

viewed : 52

Tags : csslayoutsvgpositioningmargincss

Top 5 Answer for css - How do I center an SVG in a div?

vote vote


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

vote vote


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

vote vote


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.

vote vote


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%); 
vote vote


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

  1. viewBox: defines the rectangle area for svg to cover.
  2. preserveAspectRatio: defined where to place the viewBox wrt viewport and how to strech it if viewport changes.

Follow this link from codepen for detailed description

<svg viewBox="70 160 800 190" preserveAspectRatio="xMaxYMax meet"> 

Top 3 video Explaining css - How do I center an SVG in a div?