我知道设置边际:0自动;用于使元素居中(左右)。然而,我知道元素和它的父元素必须满足自动裕度工作的某些标准,而且我似乎从来没有得到正确的魔法。
所以我的问题很简单:为了获得margin: 0 auto;左右中间的孩子?
我知道设置边际:0自动;用于使元素居中(左右)。然而,我知道元素和它的父元素必须满足自动裕度工作的某些标准,而且我似乎从来没有得到正确的魔法。
所以我的问题很简单:为了获得margin: 0 auto;左右中间的孩子?
当前回答
也许有趣的是,您不必为<button>元素指定宽度来使其工作-只需确保它具有display:block: http://jsfiddle.net/muhuyttr/
其他回答
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
如果你的父元素没有固定的宽度,让你的父元素带有display: flex对我来说很有效。
在我的脑海中,如果元素不是块元素-让它成为块元素。
然后给它一个宽度。
在我看来,它需要一个宽度。你需要指定你正在居中的容器的宽度(不是父宽度)。
它还可以与display:table一起工作——在这种情况下,这是一个有用的显示属性,因为它不需要设置宽度。(我知道这篇文章已经5年了,但它仍然与路人有关;)