gpt4 book ai didi

javascript - CSS类可以由函数生成吗?

转载 作者:行者123 更新时间:2023-11-28 02:16:49 25 4
gpt4 key购买 nike

我想创建一个使用 Bootstrap 风格的 col-* 类名的 CSS 网格模板。如果我想要 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);

Reference

在 CSS 中是否有类似的方法来实现这一点?

最佳答案

不是在纯 CSS 中,但您可以使用像 SASS 这样的 CSS 扩展:

$grid-columns: 12;

@for $i from 1 through $grid-columns {
.width-#{$i} {grid-column: span $i; }
.offset-#{$i} {grid-column-start: $i; }
}

关于javascript - CSS类可以由函数生成吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48434415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com