codecamp

LESS Multiple &

描述

通过使用运算符,可以重复引用父选择器,而不使用其名称。 在选择器中可以多次使用。


例子

下面的例子演示了在LESS文件中使用多个&:

<html>
<head>
    <title>Parent Selector</title>
	<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h2>Welcome to W3Cschool</h2>
<p class="select">It is possible to reference the parent selector by using &(ampersand) operator.</p>
<p class="select_class1">It is possible to reference the parent selector by using &(ampersand) operator</p>
</body>
</html>


接下来,创建文件 style.less

style.less

.select {
  & + & {
    color: #A9F5F2;
  }

  & & {
    color: #D0FA58;
  }

  && {
    color: #81BEF7;
  }

  &, &_class1 {
    color: #A4A4A4;
  }
}


您可以使用以下命令将 style.less 文件编译为 style.css :

lessc style.less style.css


接下来执行上面的命令,它将用下面的代码自动创建 style.css 文件:

style.css

.select + .select {
  color: #A9F5F2;
}
.select .select {
  color: #D0FA58;
}
.select.select {
  color: #81BEF7;
}
.select,
.select_class1 {
  color: #A4A4A4;
}


输出

让我们执行以下步骤,看看上面的代码如何工作:

  • 将上述html代码保存在 parent_selector.htm 文件中。

  • 在浏览器中打开此HTML文件,将显示如下输出。



&不会只代表最近的选择器,而是代表所有的父选择器。 


温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Less 基本教程

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }