How do I center an SVG in a div?

2019-01-08 05:36发布

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?

9条回答
We Are One
2楼-- · 2019-01-08 05:43

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.

查看更多
We Are One
3楼-- · 2019-01-08 05:46

I had to use

display: inline-block;
查看更多
孤傲高冷的网名
4楼-- · 2019-01-08 05:49

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

查看更多
Explosion°爆炸
5楼-- · 2019-01-08 05:49

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.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-08 05:51

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

查看更多
姐就是有狂的资本
7楼-- · 2019-01-08 05:55

Put your code in between this div if you are using bootstrap:

  <div class="text-center ">
  <i class="fa fa-twitter" style="font-size:36px "></i>
  <i class="fa fa-pinterest" style="font-size:36px"></i>
  <i class="fa fa-dribbble" style="font-size:36px"></i>
  <i class="fa fa-instagram" style="font-size:36px"></i>
  </div>
查看更多
登录 后发表回答