如何做一个.less mixin在CSS中生成网格的东西? [英] How to do a .less mixin that generates something of a grid in css?

查看:82
本文介绍了如何做一个.less mixin在CSS中生成网格的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以.cX.rY选择器的形式生成一个css选择器矩阵,用于10 x 10之类的网格.但是我没有看到如何做到这一点(我很新.较少的).我也使用DotLess,所以也许有一些内置的限制.在那方面我不确定.

I want to generate a matrix of css selector in the form of .cX.rY selectors for a grid of something like 10 x 10. But I'm not seeing how I can do this less (I'm pretty new to .less). I'm using DotLess too, so perhaps there are some built-in limitations with that; I don't know for sure on that front.

@col-width: -24px;
@row-width: -24px;


.img-pos(@col, @row) {
    background-position:
       (((@col - 1) * @col-width) - 1)
       (((@row - 1) * @row-width) - 1);
}

.c2.r1 { .img-pos(2, 1); }
.c2.r2 { .img-pos(2, 2); }
.c2.r3 { .img-pos(2, 3); }
.c2.r4 { .img-pos(2, 4); }
.c2.r5 { .img-pos(2, 5); }
.c2.r6 { .img-pos(2, 6); }
.c2.r7 { .img-pos(2, 7); }
...


...
.cX.rY { .img-pos(2, 7); }

这可能吗?如果可以,怎么办?

Is this possible? If so, how?

推荐答案

下面是一些代码,您可以设置最大列和行,还可以选择设置起始列和行号(默认值:1),还可以选择为它们设置类指示符(默认为"c"和"r").它使用LESS中的循环技术自动生成代码.

Here is some code that allows you set the max columns and rows, as well as optionally set the start column and row number (default: 1), and optionally set the class indicator for them (defaults to "c" and "r"). It uses a looping technique in LESS to auto generate the code.

LESS代码

@col-width: -24px;
@row-width: -24px;

.img-pos(@col, @row) {
    background-position:
       (((@col - 1) * @col-width) - 1)
       (((@row - 1) * @row-width) - 1);
}

.generateGridSelectors(@maxCols, @maxRows, @colStart: 1, @rowStart: 1, @colSel: "c", @rowSel: "r") when (@maxCols > 0) and (@colStart < @maxCols) and (@maxRows > 0) and (@rowStart < @maxRows) {

   @colStop: @maxCols + 1;
   @rowStop: @maxRows + 1;

   .makeGrid(@c: @colStart) when (@c < (@maxCols + 1)) {

     .setRow(@r: @rowStart) when (@r < (@maxRows + 1)) {     

     //generate selector and position
     (~".@{colSel}@{c}.@{rowSel}@{r}") {
     .img-pos(@c, @r);
     }

     //interate next row
     .setRow(@r + 1);
   }
     //end row loop
     .setRow(@rowStop) {}

     //start row loop
     .setRow();

     //iterate next column
     .makeGrid(@c + 1);

   }
   //end column loop
   .makeGrid(@colStop) {}

   //start grid loops
   .makeGrid();
} //end generateGridSelectors

//call your build (not sure how well it will handle real large numbers)
.generateGridSelectors(10, 10);

CSS输出

.c1.r1 {
  background-position: -1px -1px;
}
.c1.r2 {
  background-position: -1px -25px;
}
.c1.r3 {
  background-position: -1px -49px;
}
...
...
.c10.r8 {
  background-position: -217px -169px;
}
.c10.r9 {
  background-position: -217px -193px;
}
.c10.r10 {
  background-position: -217px -217px;
}

这篇关于如何做一个.less mixin在CSS中生成网格的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆