我想创建一个CSS Grid模板,它使用Bootstrap风格的col-*类名。如果我想要12列,我目前必须编写12个width-* & offset-*类。
假设网格具有grid-template-columns: repeat(12, 1fr)。有没有办法自动化这些类和样式,或者我必须为每个列宽度手动创建一个类?
.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;}在ES6中,我可能会草率地做这样的事情:
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);在CSS中有没有类似的方法来实现这一点?
发布于 2018-01-25 09:59:36
不是在纯CSS中,但可以使用CSS扩展,如SASS
$grid-columns: 12;
@for $i from 1 through $grid-columns {
.width-#{$i} {grid-column: span $i; }
.offset-#{$i} {grid-column-start: $i; }
}https://stackoverflow.com/questions/48434415
复制相似问题