學會如何使用LESS來征服CSS

來源:互聯網
上載者:User

今天很有雄心壯志,決定將SeaJS、Coffee、LESS都搞定。回到家後在電腦前面做了一個下午加一個晚上,悲催的發現,只解決了LESS。呃,先將LESS總結一遍。

LESS的目標是簡寫CSS。用編程的觀點去看待CSS,以OO的思想看待CSS,將常量、函數、命名空間等概念引入,使很鬆散的頁面樣式形成一個個對象,方便開發和維護。當然在寫的時候要注意技巧,不然產生的CSS將會有大量的冗餘代碼。所以只建議CSS高手進階用,初級CSSer最好還是先把CSS寫熟了再說吧!

變數和常量(Variables)

以@開始即可,只能定義屬性值。注意變數覆蓋以及範圍的問題。例如: @blue: #5b83ad; //常量 @light_blue: @nice-blue + #222; //經過計算的常量 @highlight: "blue"; #header { color: @@highlight;}//常量名為常量

函數

將每個類都看成一個函數,即可以讓別的函數調用和傳參。並且能在函數中定義子函數。

 1 .border{border: 2px solid #ccc; border-radius: 4px;} 2 .header {.border;} 3  4 //調用時一定要傳參數 5 .border(@width, @color, @radius){border: @width solid @color; border-radius: @radius;} 6 .header{.border(2px, #ccc, 4px);} 7  8 //帶預設參數 9 .border(@width:2px, @color:#ccc, @radius: 4px){10 border: @width solid @color; border-radius: @radius;11 }12 .header {.border(4px, #f00, 2px);}13 14 //@arguments 指所有參數15 .border (@width:1px, @style:solid, @color:#ccc){border: @arguments;} 16 17 #header{18 height:100px;19 &:hover {color:red;} //=== #header:hover, &代表同級20 &.top {margin-top:12px;} // === #header.top21 h1 {font-size:24px;}  // === #header h122 }23 #content {24 h1{#header h1;} //調用#header h1。這時候#header就相當於命名空間的概念25 }

注釋(Comments)

和js一樣,單行“//”和多行“/* */”。編譯時間會刪除“//”保留“/* */”。

運算

LESS的運算能力比較強大,主要有兩個方面,一個是常規四則運算(Operations),一個是顏色計算。 四則運算遵循常規的優先順序,特色是可以對顏色、數字、變數進行運算,而且對帶單位的數值有很強的容錯能力。例子: @base: 5%; @filler: @base*2; //變數運算 color: #888 / 4; //顏色運算,result === #222 @var 1px + 5; // result === 6 顏色計算主要是LESS提供了以下函數:

lighten(@color, 10%); //return lighten color darken(@color, 10%); //return darken color saturate(@color, 10%); //return more saturated desaturate(@color, 10%); //return less saturated fadein(@color, 10%); //return less transparent fadeout(@color, 10%); //return more transparent spin(@color, -10|10); //return smaller or larger than @color

提取顏色值: hue(@color); //returns the hue channel of color saturation(@color); //returns the saturation channel of @color lightness(@color); //returns the lightness channel of @color alpha(@color) //return alpha channel of @color(hsl模式裡面的透明通道) hsl(h,s,l),hsla(h,s,l,a),rgb(r,g,b),rgba(r,g,b,a) //這些更不用說,某些瀏覽器都支援了。

安裝

LESS和Coffee一樣,其實都提供了兩種安裝模式。一種是解釋模式,也就是js。通過js就能對less檔案進行編譯成正常的CSS,嵌入html頁面中。這裡的過程應該可以通過js進行配置,有空再談。而另一種就是編譯模式,安裝LESS編譯器,需要node(其實重點是npm)環境支援,進入cmd 輸入 npm install less -g 即可。解釋模式適用於開發,而編譯模式適用於發布上線。二者結合無懈可擊。coffee的安裝也類似。

作者:前端組-Elliot

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.