7

I know similar questions have been asked before but I haven't seen one where the parent div has an unknown width with a definitive answer.

So here's the situation.

<style>
.parent {
   width: 100%;
}

.child {
  width: 300px;
  float: left;
}

</style>

<div class="parent>
  <div class="child></div>
  <div class="child></div>
  <div class="child></div>
  <div class="child></div>
  <div class="child></div>
  <div class="child></div>
  ...
  <div class="child></div>
<div>

Basically, I want to fit as many child divs in the parent container as the user's screen resolution can support.

I don't want to use css3 media queries because I want to support IE7.

I tried using javascript to specify a width to the parent but it's not ideal as the content jumps to the center after it loads. Any ideas?

3 Answers3

25

Just use display:inline-block; instead of float: left; and for .parent use text-align: center.

Roman
  • 904
  • 1
  • 9
  • 19
4

This is the nearest solution without the use of javascript. It is display:inline-block; that makes divs side bar side and being in center at the same time. I've try turning .parent into display:table-cell; but didn't work. So need to use the actual <table> for the powerful centering behavior.

http://jsfiddle.net/Dgdhr/

Edited: http://jsfiddle.net/Dgdhr/1 (without table: thanks to MartinodF)

<table width="100%">
<tr>
<td align="center">   
          <div class="child">1</div>
          <div class="child">2</div>
          <div class="child">3</div>
          <div class="child">4</div>
          <div class="child">5</div>
          <div class="child">6</div>   
</td>
</tr>
</table>

.child {
    width: 100px;
    height:100px;
    margin:10px;
    display:inline-block;
    background:#e0e0e0;
}
Sovon
  • 15
  • 6
Moe Sweet
  • 3,683
  • 2
  • 34
  • 46
  • The problem with this is if you have different content within the children divs; http://jsfiddle.net/Dgdhr/76/ – Marcus Oct 28 '15 at 15:33
1

Using Roman answer I ended with this. All div inside my parent div will center, so you dont need to set child class.

.parent{
    text-align: center;
}

.parent div{
    display: inline-block;
}
Renan Ceratto
  • 130
  • 2
  • 12