less教程:http://www.bootcss.com/p/lesscss/
less中文網(wǎng):http://less.bootcss.com/
1.環(huán)境搭建
引入自己的less文件style.less(和css引入方式類似),
之后引入下載的less.js文件
<link rel="stylesheet/less" type="text/css" href="styles.less">
<script src="less.js" type="text/javascript"></script>
2.less語法
2.1 變量
//定義變量color
@color: #4D926F
#header{
color:@color;
}
h2{
color:@color;
}
相應(yīng)的css如下
#header {
color: #4D926F;
}
h2 {
color: #4D926F;
}
2.2 混合
可以定義一個樣式的函數(shù),在不同元素中調(diào)用。
//使用.方法名(參數(shù)名:值)來定義一個可以復用的方法。也可以不傳參,不需要小括號及其內(nèi)容即可
.rounded-corners(@radius:5px){
border-radius:@radius;
-weblit-border-radius:@radius;
-moz-border-radius:@radius;
}
#header{
.rounded-corners;
}
#fotter{
//傳了參數(shù)會相應(yīng)的改變變量值@radius
.rounded-corners(10px);
}
css如下:
#header {
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
}
#footer {
border-radius: 10px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
}
2.3 嵌套
我們可以在一個選擇器中嵌套另一個選擇器來實現(xiàn)繼承。
#header {
h1 {
font-size: 26px;
font-weight: bold;
}
p { font-size: 12px;
a { text-decoration: none;
&:hover { border-width: 1px }
}
}
}
對應(yīng)的css
#header h1 {
font-size: 26px;
font-weight: bold;
}
#header p {
font-size: 12px;
}
#header p a {
text-decoration: none;
}
#header p a:hover {
border-width: 1px;
}
2.4 函數(shù)和運算
@the-border: 1px;
@base-color: #111;
@red: #842210;
#header {
color: @base-color * 3;
border-left: @the-border;
border-right: @the-border * 2;
}
#footer {
color: @base-color + #003300;
border-color: desaturate(@red, 10%);
}
相應(yīng)的css
#header {
color: #333;
border-left: 1px;
border-right: 2px;
}
#footer {
color: #114411;
border-color: #7d2717;
}
2.5 模式匹配
1). 根據(jù)參數(shù)值匹配
//定義了三個mixin,參數(shù)不同,根據(jù)參數(shù)確定調(diào)用哪一個
.mixin (dark, @color) {
color: darken(@color, 10%);
}
.mixin (light, @color) {
color: lighten(@color, 10%);
}
//@_表示所有都匹配
.mixin (@_, @color) {
display: block;
}
//會調(diào)用第二個和第三個
@switch: light;
.class {
.mixin(@switch, #888);
}
css
.class {
color: #a2a2a2;
display: block;
}
2). 根據(jù)表達式匹配
- 關(guān)系運算符
.mixin (@a) when (lightness(@a) >= 50%) {
background-color: black;
}
.mixin (@a) when (lightness(@a) < 50%) {
background-color: white;
}
.mixin (@a) {
color: @a;
}
.class1 { .mixin(#ddd) }
.class2 { .mixin(#555) }
css
.class1 {
background-color: black;
color: #ddd;
}
.class2 {
background-color: white;
color: #555;
}
- 基于值的類型
.mixin (@a, @b: 0) when (isnumber(@b)) { ... }
.mixin (@a, @b: black) when (iscolor(@b)) { ... }
- 多個條件
.mixin (@a) when (isnumber(@a)) and (@a > 0) { ... }
.mixin (@a) when (@a > 10), (@a < -10) { ... }
- not關(guān)鍵字
.mixin (@b) when not (@b > 0) { ... }