Karnivaurus
Karnivaurus

Reputation: 24111

How to center a div without manually defining its width

I have some bullet points inside a div, and I want the bullet points to be aligned vertically. I also want the div to be in the center of the page. However, I do not want to have to manually define the width of the div, because I do not know in advance the size of each bullet point. How can I center the div without pre-defining the width?

The code I have so far is:

<div style='text-align:left;width:100px;margin:0 auto'>
    <ul>
        <li>Alpha</li>
        <li>Beta</li>
        <li>Gamma</li>
    </ul>
</div>

And a JSFiddle can be found at http://jsfiddle.net/7R2qJ/

(Note that in this code, the div width is manually defined, which I want to avoid).

Upvotes: 1

Views: 68

Answers (3)

Luke
Luke

Reputation: 4063

Add text-align: center to the parent, and text-align: left to the div. I find this helps in some versions of IE. Then add display: inline-block to the div too.

http://jsfiddle.net/7R2qJ/8/

<div>
    <ul>
        <li>Alpha</li>
        <li>Beta</li>
        <li>Gamma</li>
    </ul>
</div>

-

body
{
    text-align: center;
}

div
{
    background: yellow;
    text-align: left;
    margin: 0 auto;
    display: inline-block;
}

Upvotes: 1

andrew
andrew

Reputation: 9583

use the display:inline-block; property to wrap the width of the div to its content

fiddle

css

body
{
    text-align: center;
}

.list
{
    background: yellow;
    text-align: left;
    margin: 0 auto;
    display:inline-block;
}

markup

<div class="list">
    <ul>
        <li>Alpha</li>
        <li>Beta</li>
        <li>Gamma</li>
    </ul>
</div>

Upvotes: 0

Derek Story
Derek Story

Reputation: 9583

One way is to use display: table; combined with margin: 0 auto;

JS Fiddle

Upvotes: 1

Related Questions