0

I am trying to center 3 boxes in the middle of my container. However, I cannot get it working.

What am I doing wrong?

HTML

<div id="boxes">
    <div class="box">Box1</div>
    <div class="box">Box2</div>
    <div class="box">Box3</div>
</div>

CSS

#boxes {
    width: 800px;
    background-color: yellow;

    float: left;
}

#boxes .box {
    width: 100px;
    height: 100px;

    margin: 10px;
    float: left;

    background-color: blue;
}

JSFiddle with the problem: http://jsfiddle.net/3cUF5/

5 Answers5

3

If you need a crossbrowser solution, then use display: inline-block for inner boxes and align with text-align: center on parent.

Example fiddle: http://jsfiddle.net/RhBEz/1/

Css

#boxes {
    width: 800px;
    background-color: yellow;
    float: left;
    text-align: center;
}

#boxes .box {
    display: inline-block;

    width: 100px;
    height: 100px;
    margin: 10px;
    background-color: blue;
}

A second approach is using display: flex, but this will work only on recent Chrome and Firefox:

Example: http://jsfiddle.net/2mxET/1/

Css

#boxes {
    width: 800px;
    background-color: yellow;
    float: left;
    display: flex;
    justify-content:center;
}

#boxes .box {
    width: 100px;
    height: 100px;
    margin: 10px;
    background-color: blue;
}
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
1

Using float: left on .box means they cannot be centered. You also needed to add text-align: center to #boxes

Please see a working version here http://jsfiddle.net/s455x/

lukehillonline
  • 2,430
  • 2
  • 32
  • 48
1

Just add margin:0 auto; for #boxes

CSS

#boxes {
    width: 800px;
    background-color: yellow;

    float: left;
    margin-left:auto;
    margin-right:auto;
}

Now your outer container #boxes is aligned to center

Web Cruzaders
  • 41
  • 1
  • 7
0

http://jsfiddle.net/3cUF5/2/

#boxes {
    text-align: center;
}

#boxes .box {
    float: left; /* removed this line */
    display: inline-block;
}

When you're trying to center elements, it's not a good idea to use floats. You have two basic options when centering elements.

  1. do display: inline-block; to the child elements, and text-align: center; to the parent element

    or

  2. do display: block; to the element you want centered, as well as margin: 0 auto;

CRABOLO
  • 8,605
  • 39
  • 41
  • 68
0

Not sure what browsers' you are trying to support but FlexBox makes this super easy, and if non-supported browsers are a requirement then you can just provide a fallback that works.

josh_bailey4
  • 111
  • 1
  • 11