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