Center a column using Twitter Bootstrap

2018-12-31 03:11发布

How do I center a div of one column size within the container (12 columns) in Twitter Bootstrap 3.

Please see the starter fiddle.

<body class="container">
    <div class="col-lg-1 col-offset-6 centered">
        <img data-src="holder.js/100x100" alt="" />
    </div>
</body>

So, I want a div, with a class centered to be centered within the container. I may use a row if there are multiple divs, but for now I just want a div with size of one column centered within the container (12 columns).

I am also not sure the above approach is good enough as the intention is not to offset the div by half. I do not need free spaces outside the div and the contents of the div shrink in proportion. I want to empty space outside the div to be evenly distributed (shrink till the container width == one column).

30条回答
萌妹纸的霸气范
2楼-- · 2018-12-31 03:49

With Bootstrap v4, this can be accomplished just by adding .justify-content-center to the .row <div>

<div class="row justify-content-center">
    <div class="col-1">centered 1 column</div>
</div>

https://getbootstrap.com/docs/4.0/utilities/flex/#justify-content

查看更多
何处买醉
3楼-- · 2018-12-31 03:49

This is not my code, but it works perfectly (tested on Bootstrap 3) and I don't have to mess around with col-offset.

Demo:

/* centered columns styles */

.row-centered {
  text-align: center;
}

.col-centered {
  display: inline-block;
  float: none;
  /* reset the text-align */
  text-align: left;
  /* inline-block space fix */
  margin-right: -4px;
  text-align: center;
  background-color: #ccc;
  border: 1px solid #ffffd;
}
<div class="container">
  <div class="row row-centered">
    <div class="col-xs-6 col-centered">Column 6</div>
    <div class="col-xs-6 col-centered">Column 6</div>
    <div class="col-xs-3 col-centered">Column 3</div>
    <div class="col-xs-3 col-centered">Column 3</div>
    <div class="col-xs-3 col-centered">Column 3</div>
  </div>
</div>

查看更多
伤终究还是伤i
4楼-- · 2018-12-31 03:49

If you put this on your row, all of the columns inside will be centered:

.row-centered {
    display: flex;
    justify-content: space-between;
}
查看更多
ら面具成の殇う
5楼-- · 2018-12-31 03:49

Try this

<div class="row">
    <div class="col-xs-2 col-xs-offset-5"></div>
</div>

You can use other col as well like col-md-2, etc.

查看更多
柔情千种
6楼-- · 2018-12-31 03:50

Bootstrap 3 now has a built-in class for this .center-block

.center-block {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

If you are still using 2.X then just add this to your CSS.

查看更多
裙下三千臣
7楼-- · 2018-12-31 03:51

We can achieve this by using the table layout mechanism:

The mechanism is:

  1. Wrap all columns in one div.
  2. Make that div as a table with a fixed layout.
  3. Make each column as a table cell.
  4. Use vertical-align property to control content position.

The sample demo is here

Enter image description here

查看更多
登录 后发表回答