0

I'm dynamically generating more divs (of same size with same content), and I want them side by side and also center them.

Example: Assuming there can be 4 divs on one line I want it do look this:

1 div: ...[]...

2 divs: ..[][]..

3 divs: .[][][].

4 divs: [][][][]

5 divs:
[][][][]
...[]...

Is this possible?

I know you can put multiple div's in one line (and let them wrap) with float:left and an outer container with width: 100%

Test here: http://jsfiddle.net/Tyilo/cD7e3/1/

Tyilo
  • 28,998
  • 40
  • 113
  • 198
  • Could you add the tag for which language you're using to dynamically create these divs so we can better assist you? – Marty Jun 09 '11 at 23:10

3 Answers3

1

You need to place all divs in a wrapper div and use text-align:center; for the wrapper div.

EDIT:

Check out Marty's comment he's right. You would also need to do display:inline-block; for inner divs.
Babiker
  • 18,300
  • 28
  • 78
  • 125
  • I don't think text-align: center applies to block elements (divs). – Marty Jun 09 '11 at 23:02
  • Display: inline-block is for block elements with widths based on their content.. So if set widths are required then this won't work either hehe :P – Marty Jun 09 '11 at 23:13
  • @Marty Wallace - If look at his question it clearly states "of same size", we can safely assume that the SOer is setting dimensions :P – Babiker Jun 09 '11 at 23:16
  • You have the right idea. See my answer for an implementation. – thirtydot Jun 09 '11 at 23:17
  • Hm, I'd normally use float: left and display: block for columns, that's all. – Marty Jun 09 '11 at 23:20
1

Sure, that's possible:

http://jsfiddle.net/pRNgH/

I included the hacks required to make display: inline-block work in IE6/7, for more info:

Inline block doesn't work in internet explorer 7, 6

You need to ensure that you don't output whitespace between the .dynamics, or this happens.

CSS:

.divHolder {
    width: 400px;
    border: 2px solid red;
    margin: 0 0 16px 0;
    text-align: center
}
.dynamic {
    text-align: left;
    width: 100px;
    height: 50px;
    background: #ccc;

    display: inline-block;
    /* make it work in ie7 */
    *display: inline;
    zoom: 1
}

HTML:

<div class="divHolder">
    <div class="dynamic">2</div><div class="dynamic">2</div>
</div>
Community
  • 1
  • 1
thirtydot
  • 224,678
  • 48
  • 389
  • 349
0

Revised based on your comment:

If you're creating them dynamically then why can't you do:

parent width = totaldivs * div width;
parent margin: 0 auto;
Marty
  • 39,033
  • 19
  • 93
  • 162