我有一个SVG,我试图在一个div居中。div的宽度为900px。SVG的宽度为400px。SVG的左边距和右边距设置为auto。不起作用,它就像左距为0一样(默认值)。

有人知道误差是多少吗?


当前回答

这些答案对我都没用。我是这么做的。

position: relative;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);

其他回答

只需将容器视为flex,并将svg项以flex属性居中即可:

<div classname='icon'>
  <svg>.....</svg>
</div>

.icon{
  display:flex;
  align-items:center;
  justify-content:center;
 }

HTML:

<div class="wrap-center">
    <svg width="20px" height="20px"></svg>
</div>

CSS:

.wrap-center {
    display: flex;
    justify-content: center;
    align-items: center;
}

确保你的CSS如下:

margin: 0 auto;

即使您说您已经将左和右设置为auto,您可能会放置一个错误。当然我们不知道,因为你没有给我们看任何代码。

<div align="center">
  /* svg code */
</div>

这个代码中心SVG在div元素。

我必须使用

display: inline-block;