Create dynamic less mixin setting property names

2019-07-01 15:15发布

I want to create a less mixin to build up a number of margin/padding rules. I have been able to create the correct mixin for height, width, height percent and width percents. For example,

.widthX (@px) when (@px > 0) and (@px =< 30) {
    .width(@px);
    .widthX(@px - 1);
}

.widthX (@px) when (@px >= (30 + 5)) {
    .width(@px);
    .widthX(@px - 5);
}

.width (@px) { (~".w@{px}") { width: ~"@{px}px"; } }

This allows me to create explict widths or a series of width classes. The following will create CSS classes for widths 1-30 in increments of 1 and then from 30-1215 in increments of 5.

.widthX (1215);

in the CSS it properly creates:

.w1 { width: 1px; }
.w2 { width: 2px; }
// 3-29 ommitted
.w30 { width: 30px; }
.w35 { width: 35px; }
.w40 { width: 40px; }
.w45 { width: 45px; }
// etc

I want to be able to create a similiar mixin for margin and padding plus allowing me to add each side as a parameter,

.marginX (@px,@side,@abbr) when (@px > 0) {
    .margin(@px,@side,@abbr);
    .marginX(@px - 1,@side,@abbr);
}

.margin (@px,@side,@abbr) { (~".w@{abbr}@{px}") { ~"width-${side}": ~"@{px}px"; } }

and call it as:

.marginX(100,"top","t");

to create margin-top classes for 1-100px. However, I keep getting syntax error on

{ ~"width-${side}": ~"@{px}px"; } }

I have tried numerous variations and they all keep failing. I could, but really do not want to, create multiple mixins for each direction. I am hoping someone might be able to provide some suggestions that will solve my problem.

I have found this similar post: dynamic css properties in less

标签: css less
1条回答
三岁会撩人
2楼-- · 2019-07-01 15:49

LESS does not currently support dynamic CSS properties. This lack of support for dynamic properties is one point of criticism which some argue is an advantage of SASS over LESS. There do exist pull requests on certain libraries (eg, less.js) which add this capability.

Otherwise, you are pretty much stuck doing what you didn't want to do, namely:

.margin (@px,@side,@abbr) when (@side = left) {
  (~".m@{abbr}@{px}") { margin-left: ~"@{px}px"; }
}
.margin (@px,@side,@abbr) when (@side = right) { 
  (~".m@{abbr}@{px}") { margin-right: ~"@{px}px"; }
}
查看更多
登录 后发表回答