0

I would like to create a CSS Grid template that uses Bootstrap-style col-* class names. If I want 12 columns, I currently have to write 12 width-* & offset-* classes.

Assume the grid has grid-template-columns: repeat(12, 1fr). Is there a way to automate these classes and styles or do I have to manually create a class for each col width?

.width-1 {grid-column: span 1;}
.width-2 {grid-column: span 2;}
.width-3 {grid-column: span 3;}
.width-4 {grid-column: span 4;}
.width-5 {grid-column: span 5;}
.width-6 {grid-column: span 6;}
.width-7 {grid-column: span 7;}
.width-8 {grid-column: span 8;}
.width-9 {grid-column: span 9;}
.width-10 {grid-column: span 10;}
.width-11 {grid-column: span 11;}
.width-12 {grid-column: span 12;}

.offset-1 {grid-column-start: 1;}
.offset-2 {grid-column-start: 2;}
.offset-3 {grid-column-start: 3;}
.offset-4 {grid-column-start: 4;}
.offset-5 {grid-column-start: 5;}
.offset-6 {grid-column-start: 6;}
.offset-7 {grid-column-start: 7;}
.offset-8 {grid-column-start: 8;}
.offset-9 {grid-column-start: 9;}
.offset-10 {grid-column-start: 10;}
.offset-11 {grid-column-start: 11;}
.offset-12 {grid-column-start: 12;}

In ES6, I might sloppily do something like this:

const genCols = (n) => [...Array(n).keys()].map(x => {
        return`.width-${x + 1} {grid-column: span ${x + 1};}\n.offset-${x + 1} {grid-column-start: ${x + 1};}`;
    }).join('\n');

genCols(12);

Reference

Is there a similar way to accomplish this in CSS?

Owen
  • 1
  • 1
  • 1

1 Answers1

0

Not in plain CSS, but you could use a CSS extension like SASS:

$grid-columns: 12;

@for $i from 1 through $grid-columns {
  .width-#{$i} {grid-column: span $i; }
  .offset-#{$i} {grid-column-start:  $i; }
}
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156