1

I am trying to create a responsive grid. I have a 'parent' div which contains floating children. Depending on the page width a variable number of children is shown per 'row'. The children should be centered.

To get the 'parent' div to fit the children I set display:table on the parent div.

Please see the following fiddle:

http://jsfiddle.net/dwjbosman/cXuQ6/5/

css:

.page {
    background: #a00;
    width:700px;
    margin: 20px;
}
.Parent {
    background: #ccc;
    border: 1px solid black;
    display: table;
    margin-left: auto;
    margin-right:auto;
}
.Child {
    float: left;
    width: 150px;
    height: 50px;
    background:red;
    margin: 5px;
}
.br {
    clear: both;
}

html:

<div class='page'>O1
<div class="Parent">
    <div class="Child">a</div>
    <div class="Child">b</div>
    <div class="Child">c</div>
    <div class="Child">d</div>
</div>

Example O1 works as expected. However I want it to work with more floating children.

Example O2: works if I manually insert a clear: both after one row of children. This of course breaks the responsiveness of the layout.

If I leave out the 'clear' it no longer works and the result is example O3. The parent div becomes too wide and the children are no longer centered.

Is there a way to get the example O2 behavior while retaining responsive behavior?

  • I found the solution http://stackoverflow.com/questions/15950007/centering-floated-images-in-div The parent gets a `text-align:center;`. The children get a `display:inline-block` in stead of `float:left`. – user2304931 Apr 21 '13 at 20:09

1 Answers1

1

Using CSS3, you can clear every 4th .Child, starting at #5:

div.Child:nth-child(4n+5){
    clear: both;
    background-color: #ddf;
}

Browser support isn't terrible: https://developer.mozilla.org/en-US/docs/CSS/:nth-child#Browser_compatibility

I forked your fiddle: http://jsfiddle.net/ghodmode/y8g2V/

  • 2
    In your solution I still need to specify the number of children per row. I am looking for a solution in which the number of children per row is determined by the browser. – user2304931 Apr 21 '13 at 19:42