user246114
user246114

Reputation: 51611

Center divs which are floated left?

I want to center divs, something like:

<div style='width:100%;'>

    <div style='float:left; width=40px; height=40px;'></div>
    <div style='float:left; width=40px; height=40px;'></div>
    <div style='float:left; width=40px; height=40px;'></div>
    ...

</div>

While I want the child divs to be floated so they appear on the same row, I'd like them to be centered within the row horizontally. As more divs are added, they might need to eventually wrap onto another line, which is fine. But I'd like those items to be centered too. Something like:

|                    |
|  X  X  X  X  X  X  |
|        X  X        |

so in the above, enough child divs were added that the first line is completely full, then the two additional ones wrap onto another line but get centered themselves too.

What's the right style to apply here?

Thanks

Upvotes: 0

Views: 235

Answers (1)

Sruly
Sruly

Reputation: 10540

Try setting the top div (the one with width:100%;) to have text-align:center; then give each div a display:inline-block; and margin:auto;

This will work in chrome, opera, FF but not explorer.

IE only support inline-block for inline items, so to make it work in IE make the internal divs spans,

like this

<div style="width:100%;text-align:center;">
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span>
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span>
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span>
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span>
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span>
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span>
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span>
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span>
</div>

Upvotes: 1

Related Questions