混合 Mixins

混合就是将一系列属性从一个规则集引入到另一个规则集的方式,类似于 JavaScript 中的函数, 目的是提高代码的重用性。

1 普通混合

.a {
  color: red;
}
.mixin-class {
  .a();
}
.mixin-id {
  .a();
}

编译为:

.a {
  color: red;
}
.mixin-class {
  color: red;
}
.mixin-id {
  color: red;
}

2 不带输出的混合

.my-mixin {
  color: black;
}

// 该混合不会被输出
.my-other-mixin() {
  background: white;
}

.class {
  .my-mixin();
  .my-other-mixin();
}

编译为:

.my-mixin {
  color: black;
}
.class {
  color: black;
  background: white;
}

3 带参数的混合

.border-radius(@radius) {
  -webkit-border-radius: @radius;
     -moz-border-radius: @radius;
          border-radius: @radius;
}

#header {
  .border-radius(4px);
}
.button {
  .border-radius(6px);
}

编译为:

#header {
    -webkit-border-radius: 4px;
     -moz-border-radius: 4px;
          border-radius 4px;
}
.button {
    -webkit-border-radius: 6px;
     -moz-border-radius: 6px;
          border-radius 6px;
}

4 带参数并且有默认值的混合

.border-radius(@radius: 5px) {
  -webkit-border-radius: @radius;
     -moz-border-radius: @radius;
          border-radius: @radius;
}

#header {
  .border-radius();
}
.button {
  .border-radius(6px);
}

编译为:

#header {
    -webkit-border-radius: 5px;
     -moz-border-radius: 5px;
          border-radius 5px;
}
.button {
    -webkit-border-radius: 6px;
     -moz-border-radius: 6px;
          border-radius 6px;
}

5 带多个参数的混合

.mixin(@color: black; @margin, @padding: 20px) {
  color: @color;
  margin: @margin;
  padding: @padding;
}
.class1 {
  .mixin(@margin: 20px; @color: #33acfe);
}
.class2 {
  .mixin(#efca44; @padding: 40px);
}

编译为:

.class1 {
  color: #33acfe;
  margin: 20px;
  padding: 20px;
}
.class2 {
  color: #efca44;
  margin: 10px;
  padding: 40px;
}

6 @arguments 的用法

.box-shadow(@x: 0; @y: 0; @blur: 1px; @color: #000) {
  -webkit-box-shadow: @arguments;
     -moz-box-shadow: @arguments;
          box-shadow: @arguments;
}
.big-block {
  .box-shadow(2px; 5px);
}

编译为:

.big-block {
  -webkit-box-shadow: 2px 5px 1px #000;
     -moz-box-shadow: 2px 5px 1px #000;
          box-shadow: 2px 5px 1px #000;
}

results matching ""

    No results matching ""