jord8on
jord8on

Reputation: 166

Horizontally Center two divs within a container div

I found this similar question but could not get it to work.

I have two div containers labelled in my CSS as "box" and I can't get them to be centered within their parent div (labelled as "wrapper" in my CSS)

Here's my code: https://jsfiddle.net/jord8on/fjtq28g7/

CSS:

.wrapper {
  display: inline-block;
  margin: 0 auto;
}

.box {
  display: inline-block;
  width:370px;
  height: 370px;
  padding-left: 5px;
  padding-right: 5px;
  vertical-align: top;
}

Any help would be greatly appreciated!

Upvotes: 1

Views: 6971

Answers (4)

Reggie Pinkham
Reggie Pinkham

Reputation: 12708

Flexbox solution

.wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.box {
  width: 370px;
  height: 160px;
  margin: 5px;
  background: #aef;
}
<div class="wrapper">
    <div class="box">Box 1</div>
    <div class="box">Box 2</div>
</div>

Note: Add flex vendor prefixes if required by your supported browsers.

Upvotes: 2

Alexander Pulido
Alexander Pulido

Reputation: 124

flexbox is the way to go

.wrapper {
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
  margin: 0 auto;
}

.box {
  width:370px;
  height: 370px;
  padding-left: 5px;
  padding-right: 5px;
  vertical-align: top;
}

display flex will put divs side by side, and with justify content, you center both of them. Remove the display inline-block from childs to work. use mz-webkit, etc for older supporting browser

Upvotes: 2

daanvanham
daanvanham

Reputation: 249

You should change some styling for the wrapper and you'll be good:

.wrapper {
    display: block;
    text-align: center;
}

https://jsfiddle.net/fjtq28g7/3/

EDIT

If, by your comment, flexbox is still an option, you could try this:

https://jsfiddle.net/fjtq28g7/7/

The only actual changes are in the wrapper:

.wrapper {
    display: flex;
    text-align: center;
    justify-content: space-around;
    flex-wrap: wrap;
    padding: 0 3%;
}

Upvotes: 4

leofontes
leofontes

Reputation: 927

#wrapper {
    display: inline-block;
    text-align: center;
}

.box {
  display: table;
  width:370px;
  height: 370px;
  margin: 0 auto;
  padding-left: 5px;
  padding-right: 5px;
  vertical-align: top;
}

That should do it for you :D Just changed the display property to table, and gave it margin auto. Pretty common situation

====EDIT

Given your comment, here is what you should do:

.wrapper {
    display: inline-block;
    margin: 0px auto;
    width: 100%;
}

.box {
  display: table;
  width:370px;
  height: 370px;
  margin: 0 auto;
  padding-left: 5px;
  padding-right: 5px;
  vertical-align: top;
}

.box-container {
  width: 50%;
  float: left;
}

And then just wrap your .box div with the .box-container div. That way you have two 50% wide containers, and your box centered in the middle.

https://jsfiddle.net/9mzmu6r7/4/

Upvotes: 2

Related Questions