csslayoutalignmentcenter

How do I align two non-fixed width divs in the center of the browser screen?


I want to align two non-fixed width divs in the center of my screen and I want both to appear on the same horizontal plane. I would like no margin between the right edge of the left div and the left edge of the right div. So I whipped this up …

<div id="container">
   <div id="left"><%= render 'form' %></div>
   <div id="right"><%= render 'totals' %></div>
</div>

and then added this CSS

#container {
   display: block;
   margin-left: auto;
   margin-right: auto;
   text-align: center;
}

#left {
   -moz-box-sizing: border-box;
   box-sizing: border-box;
   background-color: green;
   float: left;
   display: inline-block;
}

#right {
   float: right;
   background-color: red;
   display: inline-block;
}

but disappointingly, the left DIV appears at the far left of the browser screen and the right div appears at the far right of the browser (using Chrome on Mac) and there is a wide space in between the DIVs). How can I correct the above to eliminate the space between them?


Solution

  • Get rid of your floats. Then put font-size: 0 on #container and font-size: 16px on the children.

    #container {
       font-size: 0;
    }
    #left, #right {
       font-size: 16px; //You can use font-size: initial if you don't care about IE
    }
    

    JSFiddle