Home >Web Front-end >CSS Tutorial >Why Doesn\'t `margin: auto;` Work on Inline-Block Elements?
In CSS, margin:auto; is commonly used to horizontally center block elements on a page. However, when applied to inline-block elements, this property becomes ineffective.
Inline-block elements flow into the page inline like inline elements but can have a specific width and height. This behavior creates difficulties when trying to center them horizontally using margin:auto;.
Old Code:
<code class="css">#container { /* Other styles... */ } .center { margin-left: auto; margin-right: auto; text-align: center; }</code>
In this code, the #container element has a specific width and triggers the expected centering behavior.
New Code:
<code class="css">#container { /* Other styles... */ display: inline-block; } .center { margin: 75px auto; position: relative; }</code>
Changing #container's display property to inline-block changes how it interacts with margins. Inline-block elements do not behave as block elements and lose the ability to be centered using margin:auto;.
Solution:
To center an inline-block element horizontally, use the text-align: center property on its containing element instead:
<code class="html"><div class="center"> <div class="MtopBig" id="container"></div> </div></code>
<code class="css">.center { text-align: center; }</code>
This will align the inline-block element to the center of its containing block element.
The above is the detailed content of Why Doesn\'t `margin: auto;` Work on Inline-Block Elements?. For more information, please follow other related articles on the PHP Chinese website!