less学习(三): Mixins

86 阅读1分钟

Mixins

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

转:

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

带括号的Mixins

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

结果:

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

Mixins选择器

.my-hover-mixin() {
    &:hover {
        border: 1px solid red;
    }
}
button {
    .my-hover-mixin();
}

结果:

button:hover {
    border: 1px solid red;
}

Namespaces命名空间

采用命名空间对名字进行分组,来避免重名问题。

#namespaces {
  .button {
      background-color: @blue;
      &:hover {
          background-color: darken(@blue,10%);
      }
  };
}
.class {
  color: @white;
  #namespaces > .button
}

结果:

#namespaces .button {
  background-color: #0081ff;
}
#namespaces .button:hover {
  background-color: #0067cc;
}
.class {
  color: #fff;
  background-color: #0081ff;
}
.class:hover {
  background-color: #0067cc;
}

!important

.foo (@bg: #f5f5f5; @color: #900) { 
    background: @bg; 
    color: @color; 
} 
.unimportant { 
    .foo(); 
} 
.important { 
    .foo() !important; 
}

结果

.unimportant { 
    background: #f5f5f5;
    color: #900;
} 
.important {
    background: #f5f5f5 !important; 
    color: #900 !important; 
}