Search code examples
csshtmlpositioning

Aligning 6+ divs with 3 divs per line


So i have to align some divs in a wrapper div. This is the Code:

<div id="tiles-wrapper">
    <div class="tile">asdfasdf</div>
    <div class="tile">asdfas</div>
    <div class="tile">asdf</div>
    <div class="tile">asdfasdf</div>
    <div class="tile">asdfas</div>
    <div class="tile">asdf</div>
</div>

This is my CSS Code:

/* TILES */
#tiles-wrapper{
    position: relative;
    margin-top: 20px;
    width: 960px;
    overflow: hidden;
}
.tile{
    width: 300px;
    height: 200px;
    margin-bottom: 20px;
    float: left;
    overflow: hidden;
    background-color: aqua;
}

I need to have 3 divs in one line. The first and last div in each line have to be placed at the border of the wrapper div without any padding or margin. The second div in each line should be centered with some margin on the left and right side.

The problem is that I must not have rows in my html content. I need to have all the divs lined up after each other.

The divs should be positioned like this:

|[1]------[2]-------[3]|
|[4]------[5]-------[6]|
|[7]------[8]-------[9]|
...

Is there a good CSS or JS method to do this?

Here's the fiddle: http://jsfiddle.net/STS5F/5


Solution

  • Use :nth-child(n) Selector

    .tile:nth-child(3n+1) {
        /* position of the first column */
    }
    
    .tile:nth-child(3n+2) {
        /* position of the second column */
    }
    
    .tile:nth-child(3n+0) {
        /* position of the third column */
    }