Create dynamic less mixin setting property names

自闭症网瘾萝莉.ら 提交于 2019-12-10 21:36:31

问题


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


回答1:


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"; }
}


来源:https://stackoverflow.com/questions/11928883/create-dynamic-less-mixin-setting-property-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!