0

What's the best way to center several divs?

I can conceive of a few ways, but I'm looking for the simplest, most elegant.

Here is a link to a page that is doing it:

http://soulmastery.com/#/News

I am looking for something that is IE9+ safe.


Update 1

Just to clarify, I need to vertically center the row of divs, also.

Not a duplicate, the referenced questions centers horizontally only.


Update 2

This fiddle (http://jsfiddle.net/k6ShD/4/) almost does it, with minimal CSS, but I need to get those boxes centered horizontally.

align-items: center;


Update 3

Since the question has been closed, I'll put my answer here.

I knew there had to be a good clean way to do with with CSS3:

http://jsfiddle.net/k6ShD/6/

Basically,

display:flex; 
align-items: center;
justify-content: center;

Are the keys to doing it with the flex box model.

mtyson
  • 8,196
  • 16
  • 66
  • 106

2 Answers2

1

The best way to center an arbitrary set of divs like that is to set their display mode to inline-block and set their parent to center text:

<div class="wrapper">
    <div id="box-1" class="center-me">...</div>
    <div id="box-2" class="center-me">...</div>
    <div id="box-3" class="center-me">...</div>
</div>

.wrapper {
    text-align: center;
}
.center-me {
    display: inline-block;
}
sstadt
  • 46
  • 1
1

There is no best way but many ways to do it... This one resets the margin of the first column.

    <section id="soul-masters" class="row">
        <div class="col">[col1]</div>
        <div class="col">[col2]</div>
        <div class="col">[col3]</div>
    </section>

    *:before, *:after {
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
    }
    #soul-masters {
        margin: 0 auto;
        max-width: 990px;
    }
    .row:before, .row:after {
        content: " ";
        display: table;
    }
    .row:after {
        clear: both;
    }
    .col {
        float: left;
        width: 31.3333%;
        background: gray;
        margin-left: 2%;
    }
    .col:first-child {
        margin-left: 0;
    }

http://fiddle.jshell.net/3eNds/20/ (added normalize.css to set some defaults, removed unnecessary reset margin on row container)

http://fiddle.jshell.net/3eNds/20/show/

JohanVdR
  • 2,880
  • 1
  • 15
  • 16