0

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

2
  • display: inline-block springs to mind, but I'm not sure how centering would work in that case.
    – You
    Aug 4, 2010 at 20:02
  • 1
    For starters, you should be using double quotes, not single quotes, to delimit HTML attribute values. And your inline styles are using = rather than :...
    – Matt Ball
    Aug 4, 2010 at 20:03

1 Answer 1

1

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.