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?
An <img> element is an inline element (display value of inline-block ). It can be easily centered by adding the text-align: center; CSS property to the parent element that contains it. To center an image using text-align: center; you must place the <img> inside of a block-level element such as a div .
To set text alignment in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property text-align for the center, left and right alignment.
Simply set text-align: center;
on the container.
Here's a demo.
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%);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With