Search code examples
csshtmlcss-floatcentering

Center multiple floating divs next to each other


I'm supposed to make 3 divs sit next to each other. So I made a div and I've put three divs in, with this css style:

div.holder div {
  float: left;
  width: 250px;
  background-color: yellow;   

  /*margin-right:auto;  /**These did not help**/
  margin-left:auto;  */
}

And html like this:

<div class="holder">
  <div></div>
  <div></div>
  <div></div>
</div>

And it's supposed to look like this: three divs And instead, it looks like this: three divs

The border divs should be aligned with the ending of the grey line.


Solution

  • You are specifying a pixel value for your width. No matter what you do with your floats, those pixel values are fixed and will never reach the end of the border. What you can do is set the width to a percentage like width: 33%;. You could also set your left and right margins to space out your divs like margin: 0 20px;.

    What I typically do in these situations is wrap my elements in a div and use that div for positioning the elements. Then, the inner container I will use for background colors, text colors, etc. Something like that may work for you:

    <div class="holder">
      <div class="wrapper">
         <div class="container">...</div>
      </div>
      <div class="wrapper">
         <div class="container">...</div>
      </div>
      <div class="wrapper">
         <div class="container">...</div>
      </div>
    </div>
    

    And the CSS:

    .wrapper {
        float:left;
        width:33%;
    }
    .container {
        background-color: yellow;
        margin: 10px;
        padding: 20px;
    }
    

    Here is a fiddle: http://jsfiddle.net/bWFS8/