less之經常使用語法總結

變量@

變量插值

@mySelector: banner;
.@{mySelector} {
  font-weight: bold;
}

延遲加載

變量是延遲加載的,在使用前不必定要先申明css

.brass {
   @var: 2;
   three: @var;       //這是的值是3,同級別中最後一個,順序無所謂
   @var: 3;
}

合併屬性

使用「+」,「+_」,合併同一個css樣式的屬性,前者用逗號隔開,後者用空格隔開。less

.mixin() {
  transform+_: scale(2);
}
.myclass {
  .mixin();
  transform+_: rotate(15deg);
}

=>
.myclass {
  transform: scale(2) rotate(15deg);
}

擴展 extend

nav ul {
  &:extend(.inline);
  background: blue;
}
.inline {
  color: red;
}

=>
nav ul {
  background: blue;
}
.inline,
nav ul {
  color: red;
}

混合 mixins

//混合「類」選擇器或者「id」選擇器
.a {
  color: red;
}
.mixin-class {
  .a();
}

//不輸出混合集
.my-mixin {
  color: black;
}
.my-other-mixin() {                 
  background: white;
  &:hover {
    border: 1px solid red;
  }
}
.class {
  .my-mixin;
  .my-other-mixin;
}
=>
.my-mixin {
  color: black;
}
.class {
  color: black;
  background: white;
}
.class:hover {
  border: 1px solid red;
}

//!important
.foo (@bg: #f5f5f5, @color: #900) {
  background: @bg;
  color: @color;
}
.important {
  .foo() !important;
}
=>
.important {
  background: #f5f5f5 !important;
  color: #900 !important;
}

帶參數混合

//帶參數的混合 
.border_width1(@b_width){ 
    border: solid blue @b_width; 
} 
.test_mix1{ 
    .border_width1(5px); 
} 
=>
.test_mix1 { 
    border: solid #0000ff 5px;
} 

//參數有默認值的混合 
.border_radius(@radius:5px){ 
    border-radius: @radius; 
} 
.test_radius{ 
    .border_radius(); 
    height: 20px;  
}
=>
.test_radius { 
    border-radius: 5px; 
    height: 20px;
}

//參數經過它的名稱來引用
.mixin(@color: black; @margin: 10px; @padding: 20px) {
  color: @color;
  margin: @margin;
  padding: @padding;
}
.class1 {
  .mixin(@margin: 20px; @color: #33acfe);
}
=>
.class1 {
  color: #33acfe;
  margin: 20px;
  padding: 20px;
}

模式匹配

.mixin(dark; @color) {
  color: darken(@color, 10%);
}
.mixin(light; @color) {
  color: lighten(@color, 10%);
}
.mixin(@_; @color) {
  display: block;
}

@switch: light;
.class {
  .mixin(@switch; #888);
}
有的時候,須要一次性將全部的參數所有傳進去,此時使用@arguments能夠更加方便。
//@arguments表明傳進全部的參數 
.border_arg(@c:red,@w:3px,@x:solid){ 
    border:@arguments; 
} 
.test_arg{ 
    .border_arg(40px);  
}

註釋

  • // 不會被編譯到css文件中
  • /**/ 會編譯到css文件中

避免編譯

有些狀況下,咱們不須要less中的某些內容被自動編譯,而是保留下來原樣放到CSS中,此時能夠使用~''oop

.test_avoid{
    width: ~'(300px-100px)';
}
=>
.test_avoid {
  width: (300px-100px);
}
.test{
    height: calc(~'100% - 100px');
}
=>
.test {
  height: calc(100% - 100px);
}

高級用法

循環

.loop(@counter) when (@counter > 0) {
  .loop((@counter - 1));    
  width: (10px * @counter); 
}

div {
  .loop(3);       // 調用循環
}
=>
div {
  width: 10px;
  width: 20px;
  width: 30px;
}
相關文章
相關標籤/搜索