学会如何使用LESS(二)----嵌套规则、运算、命名空间和作用域

嵌套

一、嵌套规则

header{
    h1{
        font-size: 18px;
        color: green;
    }
    .box1{
        width: 300px; height: 200px;
        background: red;
    }
}

编译后的css:

header h1 {
  font-size: 18px;
  color: green;
}
header .box1 {
  width: 300px;
  height: 200px;
  background: red;
}

二、父元素选择器(&)
表示当前选择器所有父选择器

footer{
    h1{
        font-size: 20px;
        color: orange;
    }
    .box2{
        width: 500px; height: 100px;
        background: green;
        &:hover{
            background: blue;
        }
    }
}

编译后的css:

footer h1 {
  font-size: 20px;
  color: orange;
}
footer .box2 {
  width: 500px;
  height: 100px;
  background: green;
}
footer .box2:hover {
  background: blue;
}

三、改变选择器的顺序
将&放到当前选择器之后,就会将当前选择器插入到时所有父元素之前。


.father{
    .son{
        .grand &{
            color: red;
        }
    }
}

编译后的css:

.grand .father .son {
  color: red;
}

四、组合生成所有可能的选择器列表

p,a,ul,li,span{
    border: 1px solid red;
    & &{
        border-top: 0;
    }
}

编译后的css:

p,
a,
ul,
li,
span {
  border: 1px solid red;
}
p p,
p a,
p ul,
p li,
p span,
a p,
a a,
a ul,
a li,
a span,
ul p,
ul a,
ul ul,
ul li,
ul span,
li p,
li a,
li ul,
li li,
li span,
span p,
span a,
span ul,
span li,
span span {
  border-top: 0;
}

运算

任何数值、颜色和变量都可以进行运算;
一、数值型运算
less会为你自动推算数值和单位,所以我们不用每个值都加上单位,注意,运算符与值之间必须以空格空开,涉及优先及时以()进行优先级运算;

.div{
    width: 450 + 450px;
    height: 2 * 30px;
}

.div2{
    width: ( 300px + 200 ) * 2;
}

编译后的css:

.div {
  width: 900px;
  height: 60px;
}
.div2 {
  width: 1000px;
}

二、颜色值运算
less在运算时,先将颜色值转换为rgb模式,然后再转换为16进制的颜色值并返回,rgb模式他的值是 0~255,当你的值超过255则默认使用最大值255进行计算,不能直接使用颜色名称进行运算。

.content{
    width: 300px; height: 200px;
    background: #000000 + 21;
}

编译后的css:

.content {
  width: 300px;
  height: 200px;
  background: #151515;
}

命名空间

有时候,你可能为了更好组织 CSS 或者单纯是为了更好的封装,将一些变量或者混合模块打包起来,一些属性集之后可以重复使用。

#bgcolor(){
    background: #ffffff;
    .a{
        color: #8888888;
        &:hover{
            color: #ff6600;
        }
        .b{
            background: #333;
        }
    }

}

.bgcolor1{
    background: #fdfee0;
    #bgcolor>.a;
}

.bgcolor2{
    #bgcolor>.a>.b;
}

//省略>的写法(将>改成空格即可)

编译后的css:

.bgcolor1 {
  background: #fdfee0;
  color: #8888888;
}
.bgcolor1:hover {
  color: #ff6600;
}
.bgcolor1 .b {
  background: #333;
}
.bgcolor2 {
  background: #333;
}

作用域

Less中的作用域与编程语言中的作用域概念非常相似。首先会在局部查找变量和混合,如果没找到,编译器就会在父作用域中查找,依次类推。

@color: orange;

.bgcolor{
    width: 50px;
    a{
        @color: #333;
        color: @color;
    }
    @color: red;
}

编译后的css:

.bgcolor {
  width: 50px;
}
.bgcolor a {
  color: #333333;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值