1

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/

The Codesee
  • 3,714
  • 5
  • 38
  • 78
  • Possible duplicate of [CSS center display inline block?](http://stackoverflow.com/questions/4980525/css-center-display-inline-block) / https://stackoverflow.com/search?q=inline+block+center – CBroe May 12 '16 at 19:52

3 Answers3

6

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.

Rachel S
  • 3,780
  • 3
  • 24
  • 37
  • Thanks for this, Rachel - it didn't appear to be this simple when I was searching around as all the answers seem to be long and complex _(we need more simple answers like yours!)_. Thanks again :) – The Codesee May 12 '16 at 19:41
  • My pleasure. I'm glad to have learned something new today because of your question :) – Rachel S May 12 '16 at 19:45
0

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/

Kyborek
  • 1,519
  • 11
  • 20
0

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/

Dlanor
  • 266
  • 2
  • 13