The Codesee
The Codesee

Reputation: 3783

Aligning a div to the center with display: inline-block

I have a div with the style display: inline-block - this is used to make the div automatically expand to it's content.

The div won't center using margin: 0 auto;. To troubleshoot this, I changed the element's style to display: block and width: 100px and it does center.

How am I able to center the div element which uses display: inline-block?

ul {
 list-style: none;
 margin: 0px;
 padding: 0px;
}
<div style="margin: 0 auto; display: inline-block;">
<ul>
<li>Example</li>
<li>Example</li>
<li>Example</li>
</ul>
</div>

JsFiddle: https://jsfiddle.net/8xz0sze6/2/

Upvotes: 1

Views: 10913

Answers (3)

Dlanor
Dlanor

Reputation: 276

something like that?

<div class="center" style="margin: 0 auto; display: inline-block;text-align:center;">
<ul>
<li>Example</li>
<li>Example</li>
<li>Example</li>
</ul>
</div>

ul {
 list-style: none;
 margin: 0px;
 padding: 0px;
}
ul li {
    display: inline;
}
.center {
    margin: auto;
    width: 60%;
    border: 3px solid #73AD21;
    padding: 10px;
}

https://jsfiddle.net/DlanorJQ/x0mx6efz/

Upvotes: 0

Kyborek
Kyborek

Reputation: 1511

I assume you are talking about horizontal alignment. Then you need the parent container to have text-align:center (and proper width) for the auto margin trick to work:

<div style="text-align:center;width:100%">
  <div style="margin: 0 auto; display: inline-block;">
    <ul>
      <li>Example</li>
      <li>Example</li>
      <li>Example</li>
    </ul>
  </div>
</div>

https://jsfiddle.net/6ygqqko3/

Upvotes: 0

Rachel S
Rachel S

Reputation: 3920

Add body {text-align:center;} to make the div centered on the page.

Or you can wrap this div in another div with a width of 100% and text-align center.

Upvotes: 6

Related Questions