Dom Day
Dom Day

Reputation: 2562

Centering a DIV containing unknown number of floating divs

I've read many posts on how to center a div of unknown width containing floatings divs of unknown number in another div, but all of them assume that the contained floating divs don't flow to more than one line, or they don't need to line up into nice columns.

Assuming this layout:

<div class="container">
    <div class="box">content</div>
    <div class="box">content</div>

    ... many more (unknown number) of div.box ...

    <div class="box">content</div>
    <div class="box">content</div>
</div>

where div.box has a fixed height/width, floating them left makes them line up nicely, and fill the available space as div.container is re-sized. I would like div.container to be centered however.

If I use the following, the div.box elements will all line up nicely and the div.container will be nicely centered, but the final line of divs won't line up with the left side of the other lines. They will be centered, and out of their columns.

.container {
    text-align:center;
}

.box {
    display:inline-block;
    width: 200px;
    height: 200px;
}

The width of div.container is variable, so using something like this is not an option:

.container {
    width: 1000px;
    margin: 0 auto;
}

.box {
    float: left;
    width: 200px;
    height: 200px;
}

Any ideas or suggestions ?

Upvotes: 1

Views: 239

Answers (3)

Danield
Danield

Reputation: 125523

The problem here is that becuase the container has a dynamic width - margin: 0 auto won't work.

We can fix this by using media queries for this.

FIDDLE

So lets say each box has a width of 200px the media queries will look something like:

@media (min-width: 210px) {
    ul{
        width: 200px;
    }
}

@media (min-width: 410px) {
    ul{
        width: 400px;
    }
}
...

...

Now that this is in place - margin: 0 auto on the container div works like it should.

Upvotes: 2

Samuel Backman
Samuel Backman

Reputation: 26

add this

.container {
  text-align:center;
  margin: 0 auto;
}

and make sure the parent div for the container has a width of 100%.

Upvotes: 0

Ashish Sharma
Ashish Sharma

Reputation: 342

You can use the box-sizing property to constrain the padding and border areas to the dimensions of the content box, e.g.

* {
box-sizing: border-box;
-moz-box-sizing: border-box;
}

http://jsfiddle.net/eNT2d/3/

Upvotes: 0

Related Questions