How do I center an SVG in a div?

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

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?

回答1:

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



回答2:

Above answers did not work for me. Adding the attribute preserveAspectRatio="xMidYMin" to the tag did the trick though. The viewBox attribute needs to be specified for this to work as well. Source: Mozilla developer network



回答3:

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


回答4:

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

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 and centring, so I think it's justified.



回答5:

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



回答6:

make sure your css reads:

margin: 0 auto; 

Even though you're saying you have the left and right set to auto, you may be placing an error. Of course we wouldn't know though because you did not show us any code.



回答7:

I had to use

display: inline-block; 


回答8:

You can also do this:



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!