How to align 3 divs (left/center/right) inside another div?

With that CSS, put your divs like so (floats first):

<div id="container">
  <div id="left"></div>
  <div id="right"></div>
  <div id="center"></div>
</div>

P.S. You could also float right, then left, then center. The important thing is that the floats come before the "main" center section.

P.P.S. You often want last inside #container this snippet: <div style="clear:both;"></div> which will extend #container vertically to contain both side floats instead of taking its height only from #center and possibly allowing the sides to protrude out the bottom.


Aligning Three Divs Horizontally Using Flexbox

Here is a CSS3 method for aligning divs horizontally inside another div.

#container {
  display: flex;                  /* establish flex container */
  flex-direction: row;            /* default value; can be omitted */
  flex-wrap: nowrap;              /* default value; can be omitted */
  justify-content: space-between; /* switched from default (flex-start, see below) */
  background-color: lightyellow;
}
#container > div {
  width: 100px;
  height: 100px;
  border: 2px dashed red;
}
<div id="container">
  <div></div>
  <div></div>
  <div></div>
</div>

jsFiddle

The justify-content property takes five values:

  • flex-start (default)
  • flex-end
  • center
  • space-between
  • space-around

In all cases, the three divs are on the same line. For a description of each value see: https://stackoverflow.com/a/33856609/3597276


Benefits of flexbox:

  1. minimal code; very efficient
  2. centering, both vertically and horizontally, is simple and easy
  3. equal height columns are simple and easy
  4. multiple options for aligning flex elements
  5. it's responsive
  6. unlike floats and tables, which offer limited layout capacity because they were never intended for building layouts, flexbox is a modern (CSS3) technique with a broad range of options.

To learn more about flexbox visit:

  • Methods for Aligning Flex Items
  • Using CSS flexible boxes ~ MDN
  • A Complete Guide to Flexbox ~ CSS-Tricks
  • What the Flexbox?! ~ YouTube video tutorial

Browser support: Flexbox is supported by all major browsers, except IE < 10. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add prefixes use Autoprefixer. More details in this answer.


If you do not want to change your HTML structure you can also do by adding text-align: center; to the wrapper element and a display: inline-block; to the centered element.

#container {
    width:100%;
    text-align:center;
}

#left {
    float:left;
    width:100px;
}

#center {
    display: inline-block;
    margin:0 auto;
    width:100px;
}

#right {
    float:right;
    width:100px;
}

Live Demo: http://jsfiddle.net/CH9K8/