CSS - Making Divs Center Inside Parent Container Div

Getting child divs to cooperate by centering when they are inside a parent container can be accomplished a number of ways, but it is so much easier now that we can use Flexbox property.

Initial html and css using floats

<style> i.fa, h3 { color: #ffffff; } #parent { width: 100%; text-align: center; } .child { background: #b2dd4c; margin: 0 30px 30px 0; width: 25%; float: left; } </style> <div> <div id="parent"> <div class="child"> <i class="fa fa-cogs"></i> <h3>One</h3> </div> <div class="child"> <i class="fa fa-birthday-cake"></i> <h3>Two</h3> </div> <div class="child"> <i class="fa fa-lightbulb-o"></i> <h3>Three</h3> </div> <div class="child"> <i class="fa fa-thumbs-up"></i> <h3>Four</h3> </div> <div class="child"> <i class="fa fa-puzzle-piece"></i> <h3>Five</h3> </div> <div class="child"> <i class="fa fa-pencil-square-o"></i> <h3>Six</h3> </div> </div>

Before flexbox

The child divs float nicely into rows of three, but they're not centered within the parent container

One

Two

Three

Four

Five

Six

Using Flex

We'll apply display:flex, flex-wrap:wrap (so that the divs wrap), justify-content:center to the parent and we'll remove the float:left from the child divs and will also tell them not to shrink or grow (otherwise flex will ignore the width).
Another issue we'll have is that the divs won't center perfectly because of the margin on the last div in each row. To fix that, we'll target that third div using CSS and remove the right margin.
#parent { text-align: center; border: 1px solid #b2dd4c; overflow: auto; margin: 0 auto; width: 70%; display: flex; // Initiate flexbox property flex-wrap:wrap; // Wrap within container justify-content:center // Center contents } .child { background: #b2dd4c; margin: 0 30px 30px 0; width: 25%; text-align: center; flex-grow: 0; // Don't grow flex-shrink: 0; // Don't shrink }
Another issue we'll have is that the divs won't center perfectly because of the margin on the last div in each row. To fix that, we'll target every third div using CSS and remove the right margin.
.child:nth-child(3n) { margin-right: 0%; }

Child Divs Centered Within Parent Div Container Using Flexbox

One

Two

Three

Four

Five

Six

Sticky Side Column

If you're using our PHP Website Template, this is the optional side bar column you can add to some or all of your pages. It can be useful for adding advertisements such as Adsense ads to be displayed on multiple pages.
When you include the side column, your main content will automatically adjust its width to accommodate it.
The side bar is 'sticky'; it will scroll down and remain in view.
You can turn on/off the side bar column per page by defining the $showSide option located at the top of each file.