Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

mathjax

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?

like image 986
Deets McGeets Avatar asked Sep 29 '11 18:09

Deets McGeets


People also ask

How do I center an image inline block?

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 .

How do you center inline CSS?

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.


2 Answers

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

Here's a demo.

like image 113
phihag Avatar answered Sep 19 '22 02:09

phihag


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%); 
like image 31
Ivek Avatar answered Sep 18 '22 02:09

Ivek