如何将此css编写为less mixin,自动生成所有这些类:
.class1x{margin-top:1px;}
.class2x{margin-right:1px;}
.class3x{margin-bottom:1px;}
.class4x{margin-left:1px;}
===========================================
.class1y{margin-top:2x;}
.class2y{margin-right:2px;}
.class3y{margin-bottom:2px;}
.class4ymargin-left:2px;}
===========================================
.class1n{margin-top:n..px;}
.class2n{margin-right:n..px;}
.class3n{margin-bottom:n..px;}
.class4nmargin-left:n..px;}
并增加该类和值,例如,直到值为100px。 我没有这个,但我不想为每个css属性繁殖:
@iterations: 30;
.loopingClass (@index) when (@index > 0) {
.classx@{index} { /*classx the class to add in html*/
margin: ~"@{index}px";
}
.loopingClass(@index - 1);
}
.loopingClass (0) {}
.loopingClass (@iterations);
TY。
答案 0 :(得分:6)
与given by @Bass Jobsen相同的解决方案,只需轻轻优化(它不必如此冗长):
// usage:
.class {
.make-margins(3);
// or:
// .make-margins(10, px);
// .make-margins(50, rem);
// etc.
}
// implementation:
.make-margins(@i, @u: px) when (@i > 0) {
.make-margins((@i - 1), @u);
&@{i} {.margin-x(unit(@i, @u))}
}
.margin-x(@value) {
&-1 {margin-top: @value}
&-2 {margin-right: @value}
&-3 {margin-bottom: @value}
&-4 {margin-left: @value}
}
答案 1 :(得分:2)
如果你允许(唯一)数字,你有x,y,... n,请尝试:
@iterations: 5;
@step:1;
@number: 4;
.margintype(@number,@step) when (@number = 4)
{
margin-left: ~"@{step}px";
}
.margintype(@number,@step) when (@number = 3)
{
margin-bottom: ~"@{step}px";
}
.margintype(@number,@step) when (@number = 2)
{
margin-right: ~"@{step}px";
}
.margintype(@number,@step) when (@number = 1)
{
margin-top: ~"@{step}px";
}
.writeclass(@number,@step,@loopcounter) when (@number>0)
{
.class@{loopcounter}-@{number}{
.margintype(@number,@step);
}
.writeclass(@number - 1,@step,@loopcounter);
}
.loopingClass (@index,@step,@loopcounter) when (@index > 0) {
.writeclass(@number, @index * @step,@loopcounter);
.loopingClass(@index - 1,@step,@loopcounter + 1);
}
.loopingClass (@iterations,@step,0);
结果是:
.........
.class3-4 {
margin-left: 2px;
}
.class3-3 {
margin-bottom: 2px;
}
.class3-2 {
margin-right: 2px;
}
.class3-1 {
margin-top: 2px;
}
.class4-4 {
margin-left: 1px;
}
.class4-3 {
margin-bottom: 1px;
}
.class4-2 {
margin-right: 1px;
}
.class4-1 {
margin-top: 1px;
}
答案 2 :(得分:0)
@ seven-phases-max在使用时你实际上必须使用“.class”+“sequence”+“position”。 例如,你的编译较少:
.class1-1 {
margin-top: 1px;
}
.class1-2 {
margin-right: 1px;
}
.class1-3 {
margin-bottom: 1px;
}
.class1-4 {
margin-left: 1px;
}
.class2-1 {
margin-top: 2px;
}
.class2-2 {
margin-right: 2px;
}
.class2-3 {
margin-bottom: 2px;
}
.class2-4 {
margin-left: 2px;
}
.class3-1 {
margin-top: 3px;
}
.class3-2 {
margin-right: 3px;
}
.class3-3 {
margin-bottom: 3px;
}
.class3-4 {
margin-left: 3px;
}
.make-margins(3);
值实际为iterations
。