`margin:auto;` doesn't work on inline-block elements

Math chiller picture Math chiller · Sep 29, 2013 · Viewed 30.5k times · Source

I have a "container" div to which I gave margin:auto;.

It worked fine as long as I gave it a specific width, but now I changed it to inline-block and margin:auto; stopped working

Old code (works)

New code (doesn't work)

#container {
    border: 1px solid black;
    display: inline-block;
    padding: 50px;
}
.MtopBig {
    margin: 75px auto;
    position: relative;
}
.center {
    text-align: center;
}
<div class="center MtopBig" id="container"></div>

DEMO fiddle.

Answer

jsea picture jsea · Sep 29, 2013

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>