对于那些在没有确切数字填充网格时希望将列元素居中显示在屏幕上的人,我编写了一些JavaScript代码来返回类名称:
function colCalculator(totalNumberOfElements, elementsPerRow, screenSize) {
var arrayFill = function (size, content) {
return Array.apply(null, Array(size)).map(String.prototype.valueOf, content);
};
var elementSize = parseInt(12 / elementsPerRow, 10);
var normalClassName = 'col-' + screenSize + '-' + elementSize;
var numberOfFittingElements = parseInt(totalNumberOfElements / elementsPerRow, 10) * elementsPerRow;
var numberOfRemainingElements = totalNumberOfElements - numberOfFittingElements;
var ret = arrayFill(numberOfFittingElements, normalClassName);
var remainingSize = 12 - numberOfRemainingElements * elementSize;
var remainingLeftSize = parseInt(remainingSize / 2, 10);
return ret.concat(arrayFill(numberOfRemainingElements, normalClassName + ' col-' + screenSize + '-push-' + remainingLeftSize));
}
如果您有5个元素,并且想要在md
屏幕上每行3个元素,请执行以下操作:
colCalculator(5, 3, 'md')
>> ["col-md-4", "col-md-4", "col-md-4", "col-md-4 col-md-push-2", "col-md-4 col-md-push-2"]
请记住,第二个参数必须可除以12。