Less学习教程四

             本文为http://lesscss.org/features/  Parent Selector部分的翻译。

父    选择器

&来引用父选择器(译注:大多数情况,&表示将所有的祖先选择器替换在它的位置)

&操作符最常用在嵌套规则中,表示一个应用修改类或伪类的既有选择器的父选择器,例如   

a {
  color: blue;
  &:hover {
    color: green;
  }
}

结果是:

a {
  color: blue;
}

a:hover {
  color: green;
}

请注意如果没有使用&,则上面的示例将产生a :hover规则(与<a>标记内悬停元素匹配的后代选择器),而这并不是我们通常想要使用的紧跟在a后面的:hover

“父选择器”运算符有多种用途。基本上,用于嵌入选择器的组合会比默认的情况要多见。。例如,&的另一种典型用法是产生重复的类名:

.button {
  &-ok {
    background-image: url("ok.png");
  }
  &-cancel {
    background-image: url("cancel.png");
  }

  &-custom {
    background-image: url("custom.png");
  }
}

输出:

.button-ok {
  background-image: url("ok.png");
}
.button-cancel {
  background-image: url("cancel.png");
}
.button-custom {
  background-image: url("custom.png");
}

多      多重&

&在选择器中可能会出现多次,用于重复引用父选择器而无需重复其名称。

.link {
  & + & {
    color: red;
  }

  & & {
    color: green;
  }

  && {
    color: blue;
  }

  &, &ish {
    color: cyan;
  }
}

输出为:

.link + .link {
  color: red;
}
.link .link {
  color: green;
}
.link.link {
  color: blue;
}
.link, .linkish {
  color: cyan;
}

请注意,&代表所有父选择器(而不仅仅是最接近的祖先),因此下例:

.grand {
  .parent {
    & > & {
      color: red;
    }

    & & {
      color: green;
    }

    && {
      color: blue;
    }

    &, &ish {
      color: cyan;
    }
  }
}

结果是:

.grand .parent > .grand .parent {
  color: red;
}
.grand .parent .grand .parent {
  color: green;
}
.grand .parent.grand .parent {
  color: blue;
}
.grand .parent,
.grand .parentish {
  color: cyan;
}

          更改选择器顺序

将选择器放在继承的(父)选择器之前可能很有用。这可以通过将&放在在当前选择器之后来完成。例如,在使用Modernizr时,您可能要根据支持的功能指定不同的规则:

.header {
  .menu {
    border-radius: 5px;
    .no-borderradius & {  //父子关系反过来了
      background-image: url('images/button-background.png');
    }
  }
}

选择器.no-borderradius &.no-borderradius在其父项.header .menu之前得到.no-borderradius .header .menu输出:

.header .menu {
  border-radius: 5px;
}

.no-borderradius .header .menu {
  background-image: url('images/button-background.png');
}

          组合爆发(Combinatorial Explosion)

& 也可以用于生成逗号分隔列表中选择器所有的可能排列组合:

p, a, ul, li {
  border-top: 2px dotted #366;
  & + & {
    border-top: 0;
  }
}

这将扩展为指定元素的所有可能(16种)组合:

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值