Less- 動態撰寫CSS

311581_4255714280893_1045505371_n

因為手打css熟,之前就沒在碰像這樣可以把css程式化的工具,不過最近因為想玩一些新東西,所以就把Less也順便學一下。

要使用less,可以先到http://lesscss.org/下載最新版的less。

因為它可以在client端執行,所以下載後像這樣引入就可以了。
這是你編輯的less樣式
<link rel="stylesheet/less" type="text/css" href="styles.less">
這是less.js檔案
<script src="less.js" type="text/javascript"></script>

設定完成後,就可以來玩看看less了。
可以使用變數
  1. @color#4D926F;   
  2.   
  3. #header {   
  4.   color: @color;   
  5. }   
  6. h2 {   
  7.   color: @color;   
  8. }  

Compile後
  1. #header {   
  2.   color#4D926F;   
  3. }   
  4. h2 {   
  5.   color#4D926F;   
  6. }  

使用別的樣式
  1. .rounded-corners (@radius: 5px) {   
  2.   border-radius: @radius;   
  3.   -webkit-border-radius: @radius;   
  4.   -moz-border-radius: @radius;   
  5. }   
  6.   
  7. #header {   
  8.   .rounded-corners;   
  9. }   
  10. #footer {   
  11.   .rounded-corners(10px);   
  12. }  

compile後
  1. #header {   
  2.   border-radius: 5px;   
  3.   -webkit-border-radius: 5px;   
  4.   -moz-border-radius: 5px;   
  5. }   
  6. #footer {   
  7.   border-radius: 10px;   
  8.   -webkit-border-radius: 10px;   
  9.   -moz-border-radius: 10px;   
  10. }  

巢狀結構
  1. #header {   
  2.   h1 {   
  3.     font-size26px;   
  4.     font-weightbold;   
  5.   }   
  6.   p { font-size12px;   
  7.     a { text-decorationnone;   
  8.       &:hover { border-width1px }   
  9.     }   
  10.   }   
  11. }  

compile後
  1. #header h1 {   
  2.   font-size26px;   
  3.   font-weightbold;   
  4. }   
  5. #header p {   
  6.   font-size12px;   
  7. }   
  8. #header p a {   
  9.   text-decorationnone;   
  10. }   
  11. #header p a:hover {   
  12.   border-width1px;   
  13. }  

程式化操作
  1. @the-border1px;   
  2. @base-color#111;   
  3. @red:        #842210;   
  4.   
  5. #header {   
  6.   color: @base-color * 3;   
  7.   border-left: @the-border;   
  8.   border-right: @the-border * 2;   
  9. }   
  10. #footer {    
  11.   color: @base-color + #003300;   
  12.   border-color: desaturate(@red10%);   
  13. }  

compile後
  1. #header {   
  2.   color#333;   
  3.   border-left1px;   
  4.   border-right2px;   
  5. }   
  6. #footer {    
  7.   color#114411;   
  8.   border-color#7d2717;   
  9. }  

看起來還蠻好玩的,只不過因為他是在client端運作,所以要考慮一下網頁的效能問題,也可以考慮把complie後的css再貼到一份新的css上,然後在把那份一起上傳到server的,另外也有server端的使用方法,有興趣也可以使用看看。

留言