less基本语法
less基本语法
编译
自动编译软件有很多,sublime、koala都可以,自选。
定义变量
变量使用
@test_num: 30px;
.test{
width: @test_num;
}
// 会被编译为:
.test{
width: 30px;
}
混合
样式中嵌套别的样式名,类似class控制
ul{
height: 30px;
.mix;
}
.mix{
border: 1px solid #ddd;
}
//会被编译为:
ul{
height: 30px;
border: 1px solid #ddd;
}
.mix{
border: 1px solid #ddd;
}
带参数的混合
混合的参数名是只属于当前的混合函数的,可以设置默认值;没有设置默认值的变量不可以缺省,不然会报错。
ul{
height: 30px;
.mix(15px);
}
.mix(@width: 15px){
border: @width solid #ddd;
}
//会被编译为:
ul{
height: 30px;
border: 15px solid #ddd;
}
匹配模式
类似于switch函数,可以加载传入的参数的某类css样式。若没有匹配到值,则对应语句解析为空,sublime插件会报错。
.test_pipei(red){
color: red;
}
.test_pipei(green){
color: green;
}
.test{
.test_pipei(red);
}
// 以上代码会解析为:
.test{
color: red;
}
// 若 .test{.test_pipei(green)} 则会解析为 .test{color:green}
运算
可以对数值及变量进行基础运算,颜色也可以计算不过不常用。
@num: 300px;
.test{
width: @num + 20;
}
// 以上代码会解析为:
.test{
width: 320px;
}
嵌套规则
对相应的html结构进行嵌套的css书写。
“&”代表上一层选择器。
// html结构
<ul class="test">
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
// less嵌套语法
.test{
background-color: #eee;
li{
background-color: #ddd;
a{
display: inline-block;
background-color: #ccc;
&:hover{
color: red;
}
}
}
&nali:{
margin-top: 10px;
}
}
// 以上代码解析为:
.test {
background-color: #eee
}
.test li {
list-style: none;
background-color: #ddd
}
.test li a {
display: inline-block;
background-color: #ccc
}
.test li a:hover {
color: red
}
.testnali {
margin-top: 10px
}
@arguments变量
用于全部的参数的直接使用。使用比较少。
.border_arg(@w: 30px, @c: red, @xx: solid){
border: @arguments;
}
避免编译
有时需要输出不用less编译或者less不认识的语句,就需要less对这些语句不做处理。
// ~"words" 引号内的语句将不会被less解析
.test{
width: ~"calc(30px + 20px)";
}
变量与字符串拼接
在less中定义好路径变量对路径迁移是一件非常重要的事情,所以定义路径变量非常有必要,此处就会用到路径变量与字符串之间的拼接问题。
@iconUrl: "/img";
// mixin
.c-icon(@bgImg) {
background-image: url(@bgImg);
}
.bg {
@someImgUrl: "/icon.png";
// call mixin .c-icon();
.c-icon("@{iconUrl}@{someImgUrl}");
// or below
// .c-icon("@{iconUrl}/icon.png");
}
important
在混合的样式后面加入 !important 后,该样式下的全部样式都不被添加上 !important ,用处不大,一般用于调试。
.test{
.test_detail !important;
}
.test_detail{
width: 120px;
height: 50px;
}
// 以上代码会被编译为
.test {
width: 120px!important;
height: 50px!important
}
.test_detail {
width: 120px;
height: 50px
}
vue组件中使用less语法,需要安装less依赖以及将 < <style lang="less"></style>
的语言指定为less。
THE END!