Less混合

39次阅读

共计 1257 个字符,预计需要花费 4 分钟才能阅读完成。

混合类似于编程语言中的函数。

Mixins 是一组 CSS 属性,允许我们将一个类的属性嵌套于另一个类,被嵌入的类可以看作是变量,并且包含类名作为其属性,也就是说我们可以用一个类定义样式然后把它当作变量,在另一个类中,只要引用变量的名字,就能够使用它的所有属性。

在 Less 中,可以使用类或者是 id 选择器以与 CSS 样式相同的方式声明 mixin,它可以存储多个值,并且可以在必要的时候在代码中重复使用。

注意:当我们调用 mixin 时,括号是可选的。

不输出 mixin

如果要创建一个 mixin,但是又不想要输出 mixin 的话,我们可以在它的后面加上一个括号。

    .myMixin1 {color: green;}
    .myMixin2() {background: red;}
    .allMixin {
      .myMixin1;
      .myMixin2;
    }
    
    // 输出
    .myMixin1 {color: green;}
    .allMixin {
      color: green;
      background: red;
    }

Mixins 中的选择器

Mixins 不仅可以包含属性,还可以包含选择器。

    .myxkd-mixin() {
      &:hover {
          color: red;
          font-size: 30px;
        border: 1px solid green;
      }
    }
    button {.myxkd-mixin();
    }
    
    // 输出
    button:hover {
          color: red;
          font-size: 30px;
        border: 1px solid green;
    }

命名空间

如果要在更复杂的选择器中混合属性,则可以堆叠多个 ID 或类。

    #outer {
      .inner {color: green;}
    }
    .xyz {#outer > .inner;}
    
    // 同样 > 和空白都是可选的
    #outer > .inner;
    #outer > .inner();
    #outer .inner;
    #outer .inner();
    #outer.inner;
    #outer.inner();

保护的命名空间

如果名称空间具有保护,则仅当保护条件返回 true 时,才使用由其定义的混合,命名空间保护的评估方式与 mixin 的保护方式完全相同,比如下面的两个 mixin 的工作方式就会一样的:

    #namespace when (@mode=huge) {.mixin() {/* */}
    }
    
    #namespace {.mixin() when (@mode=huge) {/* */}
    }

!important 关键字

!important 在 mixin 调用之后使用关键字将其继承的所有属性标记为 !important。

    .xkd (@bg: #f44586, @color: #d902e7) {
      background: @bg;
      color: @color;
    }
    .unimportant {.xkd();
    }
    .important {.xkd() !important;
    }
    
    // 输出
    .unimportant {
      background: #f44586;
      color: #d902e7;
    }
    .important {
      background: #f44586 !important;
      color: #d902e7 !important;
    }

正文完
 0