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

CssMathjax

Css Problem Overview


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?

Css Solutions


Solution 1 - Css

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

http://phihag.de/2011/so/inline-block-center.html">Here's a demo.

Solution 2 - Css

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 - Css

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 - Css

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeets McGeetsView Question on Stackoverflow
Solution 1 - CssphihagView Answer on Stackoverflow
Solution 2 - CssIvekView Answer on Stackoverflow
Solution 3 - CssAmie WiltView Answer on Stackoverflow
Solution 4 - CssRipcordView Answer on Stackoverflow