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

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?



Solution 1:[1]

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

Here's a demo.

Solution 2:[2]

Another way to do this (works for block element also):

.center-horizontal {
     position: absolute;
     left: 50%;
     transform: translateX(-50%);
}

Explanation: left:50% will position the element starting from the center of containing parent, so you want to pull it back by half of its width with transform: translateX(-50%)

Note1: Be sure to set the the position of containing parent to position: relative; if the parent is absolutely positioned put a 100% width and height, 0 padding and margin div inside it and give it position: relative

Note2: Can also be modified for vertical centering with

top:50%;
transform: translateY(-50%);

Solution 3:[3]

A little late, but similar to Ivek's answer, you can avoid using the position declaration by using margin-left rather than left, so:

margin-left: 50%; transform: translateX(-50%);

Solution 4:[4]

You can do this by changing it to a block element and using max-content:

.element {
  display: block; /* Change from inline-block to block */
  margin-inline: auto;
  width: max-content;
}

Using width: fit-content will also work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ivek
Solution 3 Amie Wilt
Solution 4