css預處理Less

什麼是Less?

Less其實就是css預處理器,簡單的說,就是動態編寫css。css

Less用法

首先以vue中開發爲例,先安裝less和less-loadervue

npm install less less-loader

1.變量

1.變量值定義

格式: @變量名npm

@width:100px;
  .hello{
    width: @width;
  }

最終輸出:less

.hello{
    width:100px;
  }

2.屬性變量定義

格式:@{變量名}函數

@color:color;
  .hello{
    @{color}:blue;
  }

最終輸出:code

.hello{
    color:blue;
  }

3.屬性部件變量定義

格式:@{變量名}開發

@color:color;
  .hello{
    background-@{color}: red;
  }

最終輸出:字符串

.hello{
    background-color: red;
  }

4.選擇器定義

格式:@{變量名}get

@dialog:.dialog;
  @{dialog}{
     width:80px;
     height:80px;
     background: green;
  }

最終輸出:scss

.dialog{
    width: 80px;
    height: 80px;
    background: green;
}

5.選擇器部件定義

格式:@{變量名}

@fix:fix;
  .d-@{fix}{
    color:gold;
  }

最終輸出:

.d-fix{
    color: gold;
}

2.混合(Mixins)

less中容許將已有的class或者id運用在不一樣的選擇器上

1.不帶參數

.border{
    border:2px solid blue;
  }
  .hello{
    .border;
  }

最終輸出:

.hello{
    border: 2px solid blue;
}

2.可帶參數

.border(@border-wdith){
    border:@border-wdith solid palegreen;
  }
  .hello{
    .border(20px);
  }

最終輸出:

.hello{
    border: 20px solid palegreen;
}

3.默認帶值

.border(@border-width:10px){
    border:@border-width solid blue;
  }
  .hello{
    .border();
  }

最終輸出:

.hello{
    border: 10px solid blue;
}

若是不想要默認值,能夠.border(參數值)

3.匹配模式

.pos(r){
    position: relative;
  }
  .pos(a){
    position: absolute;
  }
  .pos(f){
    position: fixed;
  }
  .hello{
    .pos(f);
  }

最終輸出:

.hello{
    position: fixed;
}

若:

.pos(@_){
    width:100px;
}

最終輸出:

.hello{
    width:100px;
    position: fixed;
}

@_表示全部的.pos都必須帶上裏面的屬性

4.運算

@width:20px;
  .hello{
    width: @width*2+10;
  }

最終輸出:

.hello{
    width: 50px;
}

5.嵌套

.list{
    li{
      width:100px;
    }
  }

最終輸出:

.list li{
    width: 100px;
}

less中懸浮:

.list{
    &:hover{
      background: red;
    }
  }

最終輸出:

.list:hover{
      background: red;
  }

注意:&在less中是表示上一層選擇器的意思

6.argument變量

.border(@border-width:3px,@x:solid,@c:black){
     border:@arguments;
  }
  .box{
    .border();
  }

最終輸出:

.box{
    border: 3px solid black;
}

@arguments就是表示()中全部參數值

7.轉義

格式:~"" 或者 ~''

@min768: ~"(min-width: 768px)";
  .hello {
    @media @min768 {
      font-size: 20px;
    }
  }

最終輸出:

@media (min-width: 768px){
    .hello{
    font-size: 20px;
}
}

當less沒法識別某個字符串的時候,就得用轉義,防止編譯錯誤

8.函數

less內置了不少用於轉換顏色、處理字符串等函數,具體見官網地址:http://lesscss.cn/functions/

9.when條件判斷

.mixin (@flag) when (@flag){
    font-weight: bold;
  }
  .hello{
    .mixin(true);
  }

最終輸出:

.hello{
     font-weight: bold;
  }

當@flag爲真的時候,就調用

相關文章
相關標籤/搜索