Less嵌套规则模仿了HTML结构,这样写可以让代码更简洁、更具层次感,上一小段代码先了解下
Less代码:
#header{
color:black;
.navigation{
font-size:12px;
}
.logo{
width:300px;
}
}
CSS编译代码:
#header {
color: black;
}
#header .navigation {
font-size: 12px;
}
#header .logo {
width: 300px;
}
使用这种方法也可以在混合中包含伪类,常见的用法就是css reset里面的清除浮动
Less代码:
.clearfix{
zoom:1;
&:after{
content:'';
display:block;
clear:both;
}
}
CSS编译代码:
.clearfix {
zoom: 1;
}
.clearfix:after {
content: '';
display: block;
clear: both;
}
其中,&运算符表示一个嵌套规则的父选择器,常用于修改一个类或者定义伪类选择器,比如:
Less代码:
a{
color:blue;
&:visited{
color:red;
}
&:hover{
color:yellow
}
}
CSS编译代码:
a {
color: blue;
}
a:visited {
color: red;
}
a:hover {
color: #ffff00;
}
在上面清除浮动的代码中,如果不加&,会是什么效果呢?
Less代码:
.clearfix{
zoom:1;
:after{
content:'';
display:block;
clear:both;
}
}
CSS编译代码:
.clearfix {
zoom: 1;
}
.clearfix :after {
content: '';
display: block;
clear: both;
}
&选择符的另一个非常重要的用途就是生产重复的类名,比如在写CSS公共样式的时候会有各种各样的button样式
Less代码:(在这里复习下less中引入路径的写法)
@p_w_picpaths:'../p_w_picpaths';
.button{
&-ok{
background:url('../p_w_picpaths/1.jpg')
}
&-cancel{
background:url('@{p_w_picpaths}/2.jpg')
}
&-custom{
background:url('@{p_w_picpaths}/3.jpg')
}
}
CSS编译代码:
.button-ok {
background: url('../p_w_picpaths/1.jpg');
}
.button-cancel {
background: url('../p_w_picpaths/2.jpg');
}
.button-custom {
background: url('../p_w_picpaths/3.jpg');
}
&选择符可以在选择器中多次出现,反复引用父选择器,而不是重复父选择器的类名
Less代码:
.link{
&+&{
color:red;
}
& &{
color:purple;
}
&&{
color:silver;
}
&, &ish{
color:pink;
}
}
CSS编译代码:
.link + .link {
color: red;
}
.link .link {
color: purple;
}
.link.link {
color: silver;
}
.link,
.linkish {
color: pink;
}
&选择符表示所有的父选择器,而不是特指最近的父选择器
Less代码:
.grand{
.parent{
&>&{
color:red;
}
& &{
color:green;
}
&&{
color:blue;
}
&,&ish{
color:black;
}
}
}
CSS编译代码:
.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代码:
p, a, ul, li {
border-top: 2px dotted #366;
& + & {
border-top: 0;
}
}
CSS编译代码:
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;
}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。