Less是CSS的扩展语言,它允许你使用变量、混合、运算、函数等特性来编写更简洁的CSS代码。
1、变量(Variables)
在Less中,可以定义变量来存储颜色、数值、字符串等,并在样式中重复使用这些变量。
1 2 3 4 5 6 7 8
| // 定义变量 @primary-color: #ff0000; @font-size: 16px;
body { color: @primary-color; // 使用变量 font-size: @font-size; }
|
2、嵌套规则(Nested Rules)
Less 支持类似Sass的嵌套CSS选择器,使代码更具层级感和清晰度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| // 嵌套规则 .header { background-color: black; .logo { width: 200px; height: 50px; } .nav { ul { list-style: none; li { display: inline-block; } } } } ```
#### 3、混合(Mixins)
混入是一种可复用的CSS代码块,可以接受参数,也可以有默认参数。
```css // 定义一个带参数的mixin .border-radius(@radius: 5px) { -webkit-border-radius: @radius; -moz-border-radius: @radius; border-radius: @radius; }
.button { .border-radius(10px); // 调用mixin并传入参数 }
.box { .border-radius(); // 如果不传入参数,则使用默认值 }
|
4、运算(Operations)
Less支持数值、颜色和单位之间的加减乘除运算。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| @base-color: #f00; @alpha: 0.1; @width: 100px;
.result-color: darken(@base-color, 10%); // 颜色运算 .result-width: @width + 20px; // 数值运算 ```
#### 5、函数(Functions)
Less提供了许多内建函数,如color manipulation(颜色操作)、math functions(数学函数)等,同时也支持自定义函数。
```css // 内置函数示例 @lighter-color: lighten(#cc3300, 20%); @darken-color: desaturate(darken(#cc3300, 10%), 20%);
// 自定义函数示例 .my-function(@size) { width: @size; height: @size; }
.square { .my-function(50px); }
|
6、导入(Import)
Less支持导入其他.less文件,类似于CSS的@import规则。
1 2 3 4 5 6 7 8
| // 导入其他Less文件 @import "variables.less"; @import "mixins.less";
body { color: @main-text-color; // 来自于variables.less .button-style(); // 来自于mixins.less }
|
以上就是Less基础语法的主要内容,掌握这些基本知识点后,就可以更高效地编写和组织CSS代码了。