居中任意数量的引导列
Posted
技术标签:
【中文标题】居中任意数量的引导列【英文标题】:Center any number of bootstrap columns 【发布时间】:2015-06-18 10:45:01 【问题描述】:我想将我的引导列居中。我可以用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
或类似的吗?
【问题讨论】:
类似问题:***.com/questions/18153234/…(但也没有动态方面) 【参考方案1】:覆盖使.col-*
浮动的默认引导样式,使其成为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>
【讨论】:
谢谢,这看起来容易多了。 (虽然我删除了偏移量......)【参考方案2】:我已经写了一个算法来计算适当的偏移量:
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++;
【讨论】:
以上是关于居中任意数量的引导列的主要内容,如果未能解决你的问题,请参考以下文章