Andrzej Gis
Andrzej Gis

Reputation: 14306

How to center a grid of divs?

To describe the problem in details I'll have to make a few assumptions:

  1. I have a list of items, which length is unknown (it can be 1, 2 or even 50)
  2. I want to display them in a grid - the items count in a row is unknown (determined by user's display resolution).
  3. Every item's width is the same and is fixed to let's say 250px.
  4. Items spacing should be determined by display resolution or the container's width should be shrunk.
  5. I don't want to use JS.

You can see exactly what I want to do at FoodGawker. I'm using 2 monitors with different resolutions. When drag and drop my browser from one to another it just puts more items in a row, but everything is still centered and symmetrical. It works also with JS disabled.

So I know it's possible, what I don't know is how to do it.

I tried many variations of float:, display:, etc, but couldn't make it work.

The code below is the closest to what I want - works fine for 2 inner divs, but for many it's no longer centered. Any ideas?

.center_wrapper {
    background: grey;
    padding: 10px;
    text-align: left;
    overflow: hidden; 
    display:inline-block;
}

.cards_wrapper {
    background: red;
    overflow: hidden; 
    margin-left: auto;
    margin-right: auto;
    text-align: center;
    width: 90%;

}
.card {
    background: blue;
    width: 250px;
    height: 250px;
    margin: auto 20px;
    display:inline;
}


<div class="cards_wrapper">
    <div class="center_wrapper">
        <div class="card">
            <img src="./Index - My ASP.NET MVC Application_files/noImageAvailable.png">
        </div>
        <div class="card">
            <img src="./Index - My ASP.NET MVC Application_files/noImageAvailable.png">
        </div>
    </div>
</div>

enter image description here

for 10

Upvotes: 2

Views: 12662

Answers (2)

MLM
MLM

Reputation: 3688

Use inline-block and a % margin

Demo: http://jsfiddle.net/MadLittleMods/9SZDC/

.block
{
    display: -moz-inline-stack;
    display: inline-block;
    vertical-align: top;
    zoom: 1;
    *display: inline;

    width: 250px;
    height: 100px;
    background: #aaeeff;

    margin: 1%;
}​

If you want to center the blocks then you can add a text-align to the container

.container
{
    text-align: center;
}

Upvotes: 13

gotohales
gotohales

Reputation: 3695

Removing the text-align: left; from .center_wrapper should do the trick.

As seen here.

Upvotes: 1

Related Questions