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

I have an element of initially unknown width, in particular, the MathJax equation provided by the user. I have an element installed as an inline unit to ensure that the width of the element matches its contents and therefore has a specific width. However, this prevents traditional centering methods. 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 in advance, and if the user clicks on the equation, I need the whole equation to be selected, so I can not set the width to 0. Does anyone have a solution for centering of this equation?

+45
css mathjax
Sep 29 '11 at 18:20
source share
3 answers

Just set text-align: center; per container.

Here is a demo .

+90
Sep 29 '11 at 18:24
source share
β€” -

Another way to do this (works with a block element as well):

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

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

Note1: Be sure to set the position containing the parent to: relative; if the parent element is absolutely positioned, set 100% width and height, 0 fill and div fields inside and give it position: relative

Note2: can also be changed for vertical centering with

 top:50%; transform: translateY(-50%); 
+18
Dec 03 '15 at 17:02
source share

A bit late, but like Ivek's answer, you can avoid the position declaration using margin-left rather than left , so:

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

+1
05 Oct '17 at 16:47 on
source share



All Articles