Is it possible to center an inline-block element and if so, how?

Deets McGeets picture Deets McGeets · Sep 29, 2011 · Viewed 89.3k times · Source

I have an element of initially unknown width, specifically a MathJax equation supplied by the user. I have the element set as inline-block to ensure that the width of the element fits its contents and so that it has a defined width. However, this prevents traditional methods of centering. That is, the following does not work:

.equationElement
{
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
}

And the solution cannot be:

.equationElement
{
    display: block;
    width: 100px;
    margin-left: auto;
    margin-right: auto;
}

Because I have no idea what the width should actually be beforehand and if the user clicks on the equation, I need the entire equation highlighted, so I cannot set the width to 0. Does anyone have a solution to centering this equation?

Answer

phihag picture phihag · Sep 29, 2011

Simply set text-align: center; on the container.

Here's a demo.