根据传递的一方(顶部,右侧,底部,左侧或全部)制作边距我有一些不足之处:
.margin(@px,@side) when (@side = top) {
(){ margin-top: ~"@{px}px"; }
}
.margin(@px,@side) when (@side = right) {
(){ margin-right: ~"@{px}px"; }
}
.margin(@px,@side) when (@side = bottom) {
(){ margin-bottom: ~"@{px}px"; }
}
.margin(@px,@side) when (@side = left) {
(){ margin-left: ~"@{px}px"; }
}
.margin(@px,@side) when (@side = all) {
(){ margin-top: ~"@{px}px";
margin-right: ~"@{px}px";
margin-bottom: ~"@{px}px";
margin-left: ~"@{px}px"; }
}
我的问题是,如果我有这样的ID:
#testfeature {
.margin(10px,l);
.margin(10px,r);
}
然后LESS就像这样编译:
#testfeature {
margin-left:10px;
}
#testfeature {
margin-right:10px;
}
如何让它像这样编译:
#testfeature {
margin-left:10px;
margin-right:10px;
}
答案 0 :(得分:2)
摆脱包含所有mixin样式的不必要的() { ... }
。它们导致选择器被奇怪地解释并将它们分成不同的选择,而不是在一个选择下连接所有内容:
.margin(@px,@side) when (@side = top) {
margin-top: ~"@{px}px";
}
.margin(@px,@side) when (@side = right) {
margin-right: ~"@{px}px";
}
.margin(@px,@side) when (@side = bottom) {
margin-bottom: ~"@{px}px";
}
.margin(@px,@side) when (@side = left) {
margin-left: ~"@{px}px";
}
.margin(@px,@side) when (@side = all) {
margin-top: ~"@{px}px";
margin-right: ~"@{px}px";
margin-bottom: ~"@{px}px";
margin-left: ~"@{px}px";
}
你可能也会放弃~"@{px}px"
而只支持@px
,也可能是最后一个mixin:
.margin(@px, @side) when (@side = all) {
margin: @px;
}
答案 1 :(得分:0)
要让它们“分组”,您需要创建一个嵌套和分组的混合。下面是一个分组的mixin函数,“简化”了边距设置。
position
然后value
(除非如下所述;它可以接受任何位置顺序,并允许auto
或inherit
的值。 0px
页边距。px
,但明确将单位设置为已通过。LESS Mixin
.setMargins(@s1: ~'', @v1: 0, @s2: ~'', @v2: 0, @s3: ~'', @v3: 0, @s4: ~'', @v4: 0) {
.setPos(top, @T) {
.setNum() when (isnumber(@T)) {
margin-top: @T * 1px;
}
.setNum() when not (isnumber(@T)){
margin-top: @T;
}
.setNum();
}
.setPos(right, @R) {
.setNum() when (isnumber(@R)) {
margin-right: @R * 1px;
}
.setNum() when not (isnumber(@R)) {
margin-right: @R;
}
.setNum();
}
.setPos(bottom, @B) {
.setNum() when (isnumber(@B)) {
margin-bottom: @B * 1px;
}
.setNum() when not(isnumber(@B)) {
margin-bottom: @B;
}
.setNum();
}
.setPos(left, @L) {
.setNum() when (isnumber(@L)) {
margin-left: @L * 1px;
}
.setNum() when not (isnumber(@L)) {
margin-left: @L;
}
.setNum();
}
//allows all to be called with one number or value
.setPos(@A, 0) when (isnumber(@A)) {
margin: @A * 1px;
}
.setPos(auto, 0) {
margin: auto;
}
.setPos(inherit, 0) {
margin: inherit;
}
//default null if no valid side given
.setPos(@other, 0) {}
//call all possible positions
.setPos(@s1, @v1);
.setPos(@s2, @v2);
.setPos(@s3, @v3);
.setPos(@s4, @v4);
}
<强>实施例强>
.setMargins(right);
生成margin-right: 0px;
.setMargins(right, 15);
生成margin-right: 15px;
.setMargins(left, 10em);
生成margin-left: 10em;
.setMargins(top, 12, right, 10);
生成:margin-top: 12px; margin-right: 10px;
.setMargins(25);
生成:margin: 25px;
.setMargins(auto);
生成:margin: auto;
所以你在选择器中使用它:
<强> LESS 强>
#testfeature {
.setMargins(left, 10, right, 10);
}
CSS输出
#testfeature {
margin-left: 10px;
margin-right: 10px;
}