LcSalazar
LcSalazar

Reputation: 16841

Centering a display:table div

I have a full width wrapper div. Inside it, there's another div set as display: table.

I've set the wrapper as text-align: center, but the table div is not getting centered. Why is that? What am I missing here in order to center the display: table div horizontally inside the wrapper?

See JsFiddle here

<div class="wrapper">
    <div class="tb">
        <div class="tb-cell">1</div>
        <div class="tb-cell">2</div>
        <div class="tb-cell">3</div>
    </div>
</div>

CSS:

.wrapper {
    width: 100%;
    background: #E0E0E0;
    text-align: center;
}

.tb {
    display: table;
    width: 100px;
    background: silver;
}

.tb-cell {
    display: table-cell;
}

Upvotes: 0

Views: 40

Answers (2)

Oriol
Oriol

Reputation: 288480

The problem is that

The text-align CSS property describes how inline content like text is aligned in its parent block element.

Then, it can't center an element with display: table, because that isn't inline content.

But you can use inline-table instead:

.tb {
    display: inline-table;
}

Demo

Upvotes: 2

Jacob
Jacob

Reputation: 2071

Add this to the class:

.tb {
    display: table;
    width: 100px;
    background: silver;
    margin: auto;
    overflow: hidden;
}

Demo: http://jsfiddle.net/gpq95d26/3/

Upvotes: 3

Related Questions