我有一个"容器" div
我给了margin:auto;
它只要我给它一个特定的工作正常width
,但现在我改变它inline-block
并且不margin:auto;
工作
#container {
border: 1px solid black;
height: 500px;
width: 650px;
}
.MtopBig {
margin-top: 75px;
}
.center {
margin-left: auto;
margin-right: auto;
text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
#container {
border: 1px solid black;
display: inline-block;
padding: 50px;
}
.MtopBig {
margin: 75px auto;
position: relative;
}
.center {
text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
jse*_*sea 29
It is no longer centered because it now flows on the page in the same way inline
elements do (very similarly to img
elements). You will have to text-align: center
the containing element to center the inline-block
div
.
什么'自动'意味着:
使用auto
水平边距将指示元素填充可用空间(来源:http://www.hongkiat.com/blog/css-margin-auto/).
为什么'display:inline-block'不会居中:
内联设置中没有可用的水平空间.在它之前和之后是占据自己空间的其他内联元素(字符).因此,该元素将表现为好像水平边距设置为零.
为什么'显示:阻止'中心:
当用作display: block
设置为它的元素时,可用的水平空间将是父元素的全宽减去元素本身的宽度.这是有道理的,因为display: block
保留了这个水平空间(从而使它'可用').请注意,元素display: block
不能彼此相邻放置.唯一的例外是在您使用时发生float
,但在这种情况下您还会得到(预期的)零利润行为,因为这会禁用水平"可用性".
"内联块"元素的解决方案:
元素display: inline-block
应该作为字符接近.中心字符/文本可以通过添加text-align: center
到其父级来完成(但您可能已经知道已经......).