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

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


当前回答

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

其他回答

在我的猫的头顶上,确保你试图居中的div没有设置为宽度:100%。

如果是,那么在子div上设置的规则才是重要的。

在我看来,它需要一个宽度。你需要指定你正在居中的容器的宽度(不是父宽度)。

在我的脑海中,如果元素不是块元素-让它成为块元素。

然后给它一个宽度。

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

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