3

Here is my html code looks alike.

<div style="width:70%; margin:0px auto; border:1px solid #000;">

<div style="float:left; width:100px; border:1px solid #000;">Test</div>
<div style="float:left; border:1px solid #000;">Test</div>

</div>

The output result looks like this.

http://imm.io/7PWG

As you can see, the wrapper div is at the center of the browser but two of the inner div are on the left side. I want them to be in the center of the wrapper div.

Any ways to do it ? Please help me out. Thanks.

spotlightsnap
  • 1,095
  • 7
  • 21
  • 26
  • 1
    This won't help your alignment issue, but I think you need to add a "clear div" after the two inner divs so that the div border is displayed around the inner divs: `
    `
    – Curtis Aug 03 '11 at 08:50

3 Answers3

3

display: inline-block can do this in a reasonably simple way:

<div style="width:70%; margin:0px auto; border:1px solid #000; overflow:hidden; text-align:center">
    <div style="display:inline-block; vertical-align:top; text-align:left">
        <div style="float:left; width:100px; border:1px solid #000;">Test</div>
        <div style="float:left; border:1px solid #000;">Test</div>
    </div>
</div>

See: http://jsfiddle.net/LJaDd/

  • I wrapped a new div around your inner two divs, and gave it display: inline-block.
  • I added text-align: center to the outer div to center the wrapper div, then added text-align: left to the wrapper div to align the text inside back to the left.
  • I added overflow: hidden to the outer div so that it contains the floated divs.
thirtydot
  • 224,678
  • 48
  • 389
  • 349
  • thanks, it's works except IE, seems like inline-block is not working cross browser ? – spotlightsnap Aug 03 '11 at 09:01
  • 1
    It only works on naturally inline elements in IE6/7, but fortunately it's easy to fix, [see here](http://stackoverflow.com/questions/5838454/inline-block-doesnt-work-in-internet-explorer-7-6/5838575#5838575). Here's a fixed version of the demo in my answer that does work in IE6/7: http://jsfiddle.net/LJaDd/1/ – thirtydot Aug 03 '11 at 09:05
0

I think this will be helpful: http://www.pmob.co.uk/pob/centred-float.htm

lamelas
  • 872
  • 6
  • 15
0

try this ...

<div style="width:70%; margin:0px auto; border:1px solid #000; background-color: yellow;">
    <div>
        <div style="float:left;width:100px; border:1px solid #000;">Test</div>
        <div style="float:left;border:1px solid #000;">Test</div>
    </div>
</div>

the float:left was causing your inner 2 divs to go all the way to the left and not be centered. By putting those inside another div that fixes it.

here it is in action ... http://jsfiddle.net/sixgun/mp3T2/

Antony Scott
  • 21,690
  • 12
  • 62
  • 94