Aaronmacaron Aaronmacaron - 4 months ago 15
CSS Question

Bootstrap center all columns in whole row

I'm currently creating a web page with Bootstrap and I'm using columns. My page looks like that:

My Page

I'd like to center the last column (in the second row) but the page is dynamic and I don't know how many containers there are.

I found this two solutions on Google:

1) Add this to my css:

.col-centered{
float: none;
margin: 0 auto;
}


2) Add this to the class tag attribute

col-lg-offset-4




But both solutions look like this:

My page

That is not what i want. I want it to look like this:

enter image description here



How can i achieve this?

Answer

Bootstrap's columns are floating by default with css float property. With float we can't middle align columns. However with display: inline-block we can. All we need is to remove float from styles of columns and change them to inline-block with vertical-align: middle and you will get what you want. But don't forget to remove extra space that comes with inline-block.

Here is the trick.

.wrapper {
  background: green;
  padding: 20px 0;
}

.box {
  border-radius: 10px;
  margin-bottom: 30px;
  background: #fff;
  padding: 10px;
  color: #000;
}

.center-align {
  letter-spacing: -4px;
  text-align: center;
  font-size: 0;
}

.center-align [class*='col-'] {
  display: inline-block;
  vertical-align: top;
  letter-spacing: 0;
  font-size: 14px;
  float: none;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="wrapper">
  <div class="container center-align">
    <div class="row">
      <div class="col-xs-4">
        <div class="box">
          <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</p>
        </div>
      </div>
      <div class="col-xs-4">
        <div class="box">
          <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</p>
        </div>
      </div>
      <div class="col-xs-4">
        <div class="box">
          <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</p>
        </div>
      </div>
      <div class="col-xs-4">
        <div class="box">
          <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</p>
        </div>
      </div>
    </div>
  </div>
</div>

Note: Setting font-size: 0; letter-spacing: -4px on parent and applying parent's font-size: 14px; letter-spacing: 0 back on child elements will remove white space that comes with inline-block.

Comments