Two Divs on the same row and center align both of them

knightrider picture knightrider · Aug 2, 2011 · Viewed 129.8k times · Source

I have two divs like this

<div style="border:1px solid #000; float:left">Div 1</div>
<div style="border:1px solid red; float:left">Div 2</div>

I want them to display on the same row, so I used float:left.

I want both of them to be at center of the page as well, so I tried to wrap them with another div like this

<div style="width:100%; margin:0px auto;">
  <div style="border:1px solid #000; float:left">Div 1</div>
  <div style="border:1px solid red; float:left">Div 2</div>
</div>

But it doesn't work. If I change the code to this

<div style="width:100%; margin-left:50%; margin-right:50%">
  <div style="border:1px solid #000; float:left">Div 1</div>
  <div style="border:1px solid red; float:left">Div 2</div>
</div>

then it's going to the center, but the horizontal scrollbar is there and it seems like it's not really centered as well.

Can you please kindly suggest to me how can I achieve this? Thanks.

Edit: I want the inner div (Div 1 and Div 2) to be center align as well.

Answer

Jason Gennaro picture Jason Gennaro · Aug 2, 2011

You could do this

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>  

http://jsfiddle.net/jasongennaro/MZrym/

  1. wrap it in a div with text-align:center;
  2. give the innder divs a display:inline-block; instead of a float

Best also to put that css in a stylesheet.