我知道设置边际:0自动;用于使元素居中(左右)。然而,我知道元素和它的父元素必须满足自动裕度工作的某些标准,而且我似乎从来没有得到正确的魔法。

所以我的问题很简单:为了获得margin: 0 auto;左右中间的孩子?


当前回答

如果你的父元素没有固定的宽度,让你的父元素带有display: flex对我来说很有效。

其他回答

也许有趣的是,您不必为<button>元素指定宽度来使其工作-只需确保它具有display:block: http://jsfiddle.net/muhuyttr/

请查看我创建的jsFiddle的快速示例。希望这很容易理解。您可以使用包装div与网站的宽度居中对齐。你必须设置宽度的原因是,这样浏览器就知道你不是在使用流动布局。

CSS的完整规则:

(显示:块和宽度不是自动的)或显示:表 浮:没有 位置:相对或位置:静态

OR

带有display: flex的父元素

For anybody just now hitting this question, and not being able to fix margin: 0 auto, here's something I discovered you may find useful: a table element with no specified width must have display: table and not display: block in order for margin: auto to do work. This may be obvious to some, as the combination of display: block and the default width value will give a table which expands to fill its container, but if you want the table to take it's "natural" width and be centered, you need display: table

以下是我的建议:

First: 
      1. Add display: block or table
      2. Add position: relative
      3. Add width:(percentage also works fine)
Second: 
      if above trick not works then you have to add float:none;