`margin:auto;` doesn't work on inline-block elements
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
.
#container {
border: 1px solid black;
display: inline-block;
padding: 50px;
}
.MtopBig {
margin: 75px auto;
position: relative;
}
.center {
text-align: center;
}
<div class="center">
<div class="MtopBig" id="container"></div>
</div>
What 'auto' means:
Using auto
for the horizontal margin will instruct the element to fill up the available space (source: http://www.hongkiat.com/blog/css-margin-auto/).
Why 'display: inline-block' does not center:
There is no available horizontal space in an inline setting. Before and after it are other inline elements (characters) that take up their own space. Therefore, the element will act as if the horizontal margin is set to zero.
Why 'display: block' centers:
When used as an element with display: block
set to it, the available horizontal space will be the full width of the parent element minus the width of the element itself. This makes sense because display: block
is reserving this horizontal space (thus making it 'available'). Note that elements with display: block
cannot be placed next to each other. The only exception occurs when you use float
, but in that case you also get the (expected) zero-margin-behaviour, as this disables the horizontal 'availability'.
Solution for 'inline-block' elements:
Elements with display: inline-block
should be approached as characters. Centering characters/text can be done by adding text-align: center
to their parent (but you probably knew that already...).
For elements with property display: inline-block; A computed value of 'auto' for 'margin-left' or 'margin-right' becomes a used value of '0'. [reference: CSS2§10.3.9]