Less嵌套规则模仿了HTML结构,这样写可以让代码更简洁、更具层次感,上一小段代码先了解下
Less代码:
1
2
3
4
5
6
7
8
9
|
#header{
color
:
black
;
.navigation{
font-size
:
12px
;
}
.logo{
width
:
300px
;
}
}
|
CSS编译代码:
1
2
3
4
5
6
7
8
9
|
#header {
color
:
black
;
}
#header .navigation {
font-size
:
12px
;
}
#header .logo {
width
:
300px
;
}
|
使用这种方法也可以在混合中包含伪类,常见的用法就是css reset里面的清除浮动
Less代码:
1
2
3
4
5
6
7
8
|
.clearfix{
zoom:
1
;
&:after{
content
:
''
;
display
:
block
;
clear
:
both
;
}
}
|
CSS编译代码:
1
2
3
4
5
6
7
8
|
.clearfix {
zoom:
1
;
}
.clearfix:after {
content
:
''
;
display
:
block
;
clear
:
both
;
}
|
其中,&运算符表示一个嵌套规则的父选择器,常用于修改一个类或者定义伪类选择器,比如:
Less代码:
1
2
3
4
5
6
7
8
9
|
a{
color
:
blue
;
&:visited{
color
:
red
;
}
&:hover{
color
:yellow
}
}
|
CSS编译代码:
1
2
3
4
5
6
7
8
9
|
a {
color
:
blue
;
}
a:visited {
color
:
red
;
}
a:hover {
color
:
#ffff00
;
}
|
在上面清除浮动的代码中,如果不加&,会是什么效果呢?
Less代码:
1
2
3
4
5
6
7
8
|
.clearfix{
zoom:
1
;
:after{
content
:
''
;
display
:
block
;
clear
:
both
;
}
}
|
CSS编译代码:
1
2
3
4
5
6
7
8
|
.clearfix {
zoom:
1
;
}
.clearfix :after {
content
:
''
;
display
:
block
;
clear
:
both
;
}
|
不难发现,这是一个典型的后代选择器,并不是我们想要的效果
&选择符的另一个非常重要的用途就是生产重复的类名,比如在写CSS公共样式的时候会有各种各样的button样式
Less代码:(在这里复习下less中引入路径的写法)
1
2
3
4
5
6
7
8
9
10
11
12
|
@images:
'../images'
;
.button{
&-ok{
background
:
url
(
'../images/1.jpg'
)
}
&-cancel{
background
:
url
(
'@{images}/2.jpg'
)
}
&-custom{
background
:
url
(
'@{images}/3.jpg'
)
}
}
|
CSS编译代码:
1
2
3
4
5
6
7
8
9
|
.button-ok {
background
:
url
(
'../images/1.jpg'
);
}
.button-cancel {
background
:
url
(
'../images/2.jpg'
);
}
.button-custom {
background
:
url
(
'../images/3.jpg'
);
}
|
&选择符可以在选择器中多次出现,反复引用父选择器,而不是重复父选择器的类名
Less代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
.link{
&+&{
color
:
red
;
}
& &{
color
:
purple
;
}
&&{
color
:
silver
;
}
&, &ish{
color
:pink;
}
}
|
CSS编译代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
.link + .link {
color
:
red
;
}
.link .link {
color
:
purple
;
}
.link.link {
color
:
silver
;
}
.link,
.linkish {
color
: pink;
}
|
&选择符表示所有的父选择器,而不是特指最近的父选择器
Less代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
.grand{
.parent{
&>&{
color
:
red
;
}
& &{
color
:
green
;
}
&&{
color
:
blue
;
}
&,&ish{
color
:
black
;
}
}
}
|
CSS编译代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
.grand .parent > .grand .parent {
color
:
red
;
}
.grand .parent .grand .parent {
color
:
green
;
}
.grand .parent.grand .parent {
color
:
blue
;
}
.grand .parent,
.grand .parentish {
color
:
black
;
}
|
&选择符还可以用于生成一个逗号分割列表的所有可能的选择器排列
Less代码:
1
2
3
4
5
6
|
p, a, ul, li {
border-top
:
2px
dotted
#366
;
& + & {
border-top
:
0
;
}
}
|
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
|
p,
a,
ul,
li {
border-top
:
2px
dotted
#366
;
}
p + p,
p + a,
p + ul,
p + li,
a + p,
a + a,
a + ul,
a + li,
ul + p,
ul + a,
ul + ul,
ul + li,
li + p,
li + a,
li + ul,
li + li {
border-top
:
0
;
}
|
本文转自 frwupeng517 51CTO博客,原文链接:http://blog.51cto.com/dapengtalk/1858058