LESS mixin

时间:2017-02-09 17:01:44

标签: css less

问题

我创建了以下mixin:

.type(@style;@mb) {
    & when (@style = hero) {
        margin-bottom: @mb;
        font-size: 2.625rem;
        line-height: 1.238095238;
    }
}

现在这主要是我想要的东西。我遇到的问题有时候我会想要声明@mb值,但很多时候我都不会。在这些情况下,我希望回退到每个@style参数的预定值。

例如:

  • 对于hero@mb默认为margin-bottom: 1.25rem;
  • 对于page@mb默认为margin-bottom: 1.125rem;

期望的结果

期望的结果如下:

.sample-class-01 { .type(hero); }
.sample-class-02 { .type(page,0); }

我会得到以下输出:

.sample-class-01 { 
    margin-bottom: 1.25rem;
    font-size: 2.625rem;
    line-height: 1.238095238;
}
.sample-class-02 {
    margin-bottom: 0;
    font-size: 2rem;
    line-height: 1.3125;
}

如何创建此mixin?

2 个答案:

答案 0 :(得分:2)

只需为每个样式集进行mixin特化/重载:

.type(hero, @mb: 1.25rem) {
    margin-bottom: @mb;
    font-size: 2.625rem;
    line-height: 1.238095238;
}

.type(not-a-hero, @mb: 2.22rem) {
    margin-bottom: @mb;
    font-size: 3.333rem;
    line-height: 4.444444444;
}

// etc.

参考:

答案 1 :(得分:0)

这样的事情:

.type(@style; @mb: '') {
    & when (@style = hero) {
      font-size: 42px;              // 42px
      line-height: 52px;       // 52px

      & when not (@mb = '') { margin-bottom: @mb; }
      & when (@mb = '') { margin-bottom: 1.25rem; }
    }

    & when (@style = footer) {
      font-size: 22px;              // 42px
      line-height: 32px;       // 52px

      & when not (@mb = '') { margin-bottom: @mb; }
      & when (@mb = '') { margin-bottom: 1.125rem; }
    }
}

.sample-class-1 { .type(hero); }
.sample-class-2 { .type(hero,0); }
.sample-class-3 { .type(hero,3rem); }


.sample-class-4 { .type(footer); }
.sample-class-5 { .type(footer,0); }
.sample-class-6 { .type(footer,3rem); }

应编译为:

.sample-class-1 {
  font-size: 42px;
  line-height: 52px;
  margin-bottom: 1.25rem;
}
.sample-class-2 {
  font-size: 42px;
  line-height: 52px;
  margin-bottom: 0;
}
.sample-class-3 {
  font-size: 42px;
  line-height: 52px;
  margin-bottom: 3rem;
}
.sample-class-4 {
  font-size: 22px;
  line-height: 32px;
  margin-bottom: 1.125rem;
}
.sample-class-5 {
  font-size: 22px;
  line-height: 32px;
  margin-bottom: 0;
}
.sample-class-6 {
  font-size: 22px;
  line-height: 32px;
  margin-bottom: 3rem;
}

Less2css link