将任意数量的 bootstrap 列居中

Center any number of bootstrap columns

我想将 bootstrap 列居中。我可以用 offsets:

<div class="row">
    <div class="col-lg-2 col-sm-4 col-xs-6  col-lg-offset-3">Col1</div>
    <div class="col-lg-2 col-sm-4 col-xs-6">Col 2</div>
    <div class="col-lg-2 col-sm-4 col-xs-6 col-xs-offset-3 col-sm-offset-0 ">Col 3</div>
</div>

但是,列数是数据驱动的,所以我无法提前知道正确的偏移量。是否有 pull-center 或类似的东西?

我已经写了一个算法来计算适当的偏移量:

function boostrap_calc_offset($ind, $nb_total, $nb_per_row) {
    $offsets = array();
    foreach ($nb_per_row as $size => $n) {
        $offsets[$size] = 0;

        if ($ind % $n == 0) {
            if ($nb_total - $ind - $n > 0)
                $in_this_row = $n;
            else 
                $in_this_row = $nb_total - $ind;

            if ($in_this_row < $n) {
                $o = (12 - (12 / $n) * $in_this_row) / 2;
                $offsets[$size] = $o;
            }
        }
    }

    $offset = '';
    foreach ($offsets as $size => $o) {
        $offset .= ' col-' . $size . '-offset-' . $o;
    }

    return $offset;
}

使用方法:

$nb_per_row = array('lg' => 6, 'sm' => 3, 'xs' => 2);
$nb = count($data);

$i = 0;
foreach ($data as $datum) {
    $content .= '<div class="col-lg-2 col-sm-4 col-xs-6 ' . boostrap_calc_offset($i, $nb, $nb_per_row) .'">...</div>';
    $i++;
}

覆盖使 .col-* 浮动的默认 bootstrap 样式,使其成为 display: inline-block;,然后将 text-align: center; 应用于父元素

[class^="col-"],
[class*=" col-"] {
  float: none !important;
  display: inline-block;
}
.row {
  text-align: center;
  background-color: #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

<div class="row">
  <div class="col-lg-2 col-sm-4 col-xs-6  col-lg-offset-3">Col1</div>
</div>
<div class="row">
  <div class="col-lg-2 col-sm-4 col-xs-6">Col 2</div>
  <div class="col-lg-2 col-sm-4 col-xs-6">Col 2</div>
</div>
<div class="row">
  <div class="col-lg-2 col-sm-4 col-xs-6 col-xs-offset-3 col-sm-offset-0 ">Col 3</div>
</div>