1

I would like to center my bootstrap columns. I could do so with 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>

However, the number of columns is data-driven, so I can't know the right offset in advance. Is there a pull-center or something similar?

Community
  • 1
  • 1
giraff
  • 4,601
  • 2
  • 23
  • 35
  • Similar question: http://stackoverflow.com/questions/18153234/center-a-column-using-twitter-bootstrap-3 (but also without the dynamic aspect) – giraff Apr 13 '15 at 07:30

2 Answers2

3

Overwrite default bootstrap style that makes .col-* float, make it display: inline-block;, then apply text-align: center; to parent element

[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>
Justinas
  • 41,402
  • 5
  • 66
  • 96
0

I have written an algorithm to calculate the appropriate offset:

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;
}

How to use it:

$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++;
}
giraff
  • 4,601
  • 2
  • 23
  • 35