我通常会写SASS,但对于特定的项目,我必须使用LESS。
如何使用less实现以下内容?使用sass可以调用mixin,如@include align(hcenter top),将元素水平放置在中间和顶部。
@mixin align($styles) {
position: absolute;
content: '';
display: block;
@each $style in $styles {
@if ($style == center) {
margin-left: auto;
margin-right: auto;
margin-top: auto;
margin-bottom: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
@if ($style == hcenter) {
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
}
@if ($style == vcenter) {
margin-top: auto;
margin-bottom: auto;
top: 0;
bottom: 0;
}
@if ($style == top) {
top: 0;
}
@if ($style == bottom) {
bottom: 0;
}
@if ($style == right) {
right: 0;
}
@if ($style == left) {
left: 0;
}
}
}
答案 0 :(得分:2)
请参阅Mixin Arguments,List Functions和Loops。
使用"for"之类的内容,代码段可以转换为:
@import "loops/for";
#usage {
.align(hcenter, top, bottom, etc);
}
.align(@styles...) {
position: absolute;
content: '';
display: block;
.for(@styles); .-each(@style) {
& when (@style = center) {
margin-left: auto;
margin-right: auto;
margin-top: auto;
margin-bottom: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
& when (@style = hcenter) {
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
}
& when (@style = vcenter) {
margin-top: auto;
margin-bottom: auto;
top: 0;
bottom: 0;
}
& when (@style = top) {
top: 0;
}
& when (@style = bottom) {
bottom: 0;
}
& when (@style = right) {
right: 0;
}
& when (@style = left) {
left: 0;
}
}
}
实际上,上面的代码可以优化为更紧凑:
.align(@styles...) {
position: absolute;
content: '';
display: block;
.center(@pos) {
margin-@{pos}: auto;
@{pos}: 0;
}
.for(@styles);
.-each(center) {.-each(hcenter); .-each(vcenter)}
.-each(hcenter) {.center(left); .center(right)}
.-each(vcenter) {.center(top); .center(bottom)}
.-each(@style) when (default()) {@{style}: 0}
}
虽然这种方式对于不太熟悉Less的人来说可能会让人感到困惑。
答案 1 :(得分:0)
我不确定你的每个循环。例如,(center, top;)
会将top: 0;
设置两次?
但你可以尝试:
.align(@styles){
.setproperties(@iterator:1) when (@iterator <= length(@styles)) {
@style: extract(@styles,@iterator);
& when (@style = center) {
margin-left: auto;
margin-right: auto;
margin-top: auto;
margin-bottom: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
& when (@style = hcenter)
{
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
}
// add more & when 's here
.setproperties((@iterator + 1));
}
position: absolute;
content: '';
display: block;
.setproperties();
}
以上可以通过以下方式调用:
selector1 {
.align(center;);
}
selector2 {
.align(center hcenter;);
}