如何通过使用不同的参数来改变较少的属性?

时间:2017-04-17 03:45:00

标签: css less

我经常使用较少的相似性,例如:

.position{
  position:absolute;
  right:10px;
  top:20px;
}

所以我想使用mixin

.position(@absolute:absolute;@top:0;@right:0;@bottom:0;@left:0){
    position: @absolute;
    top:@top;
    right: @right;
    bottom:@bottom;
    left:@left;
}

但有时我不需要right,但该函数始终将right注入我的代码中。

如果我想拥有以下代码,我应该怎么做:

.position(@absolute:absolute;@top:12px;@left:12px;@bottom:12px);
//without 'right'
.position{
    position: absolute;
    top:12px;
    bottom:12px;
    left:12px;
}

谢谢!

1 个答案:

答案 0 :(得分:1)

你可以像这样重写你的mixin(它没有任何必需的参数):

.position(
  @position: absolute;
  @top: false;
  @right: false;
  @bottom: false;
  @left: false
){
  position: @position;

  & when not (@top = false) {
    top: @top;
  }

  & when not (@right = false) {
    right: @right;
  }

  & when not (@bottom = false) {
    bottom: @bottom;
  }

  & when not (@left = false) {
    left: @left;
  }
}

现在你只能设置你真正需要的那些参数:

a {
  .position(
    @top: 20px, 
    @left: 0px
  );
}

b {
  .position(
    @bottom: -50px, 
    @right: 0
  );
}

Css输出:

a {
  position: absolute;
  top: 20px;
  left: 0px;
}
b {
  position: absolute;
  right: 0;
  bottom: -50px;
}