LESS - 父选择器
描述
父选择器运算符有很多用途,例如,当您需要以非默认方式组合嵌套规则的选择器时。&的另一个典型用途是重复生成类名。
示例
以下示例演示了如何在 LESS 文件中重复生成类名 −
<html>
<head>
<link rel = "stylesheet" href = "style.css" type = "text/css" />
<title>Parent Selector</title>
</head>
<body>
<h2>Welcome to TutorialsPoint</h2>
<p class = "select-first">It is possible to reference the parent
selector by using &(ampersand) operator.</p>
<p class = "select-second">It is possible to reference the
parent selector by using &(ampersand) operator</p>
<p class = "select-third">It is possible to reference the
parent selector by using &(ampersand) operator.</p>
</body>
</html>
现在创建 style.less 文件。
style.less
.select {
&-first {
background-color: #58D3F7;
}
&-second {
background-color: #F5F6CE;
}
&-third {
background-color: #F5A9E1;
}
}
您可以使用以下命令将 style.less 文件编译为 style.css −
lessc style.less style.css
执行上述命令;它将使用以下代码自动创建 style.css 文件 −
style.css
.select-first {
background-color: #58D3F7;
}
.select-second {
background-color: #F5F6CE;
}
.select-third {
background-color: #F5A9E1;
}
输出
按照以下步骤查看上述代码的工作原理 −
将上述 html 代码保存在 parent_selector22.htm 文件中。
在浏览器中打开此 HTML 文件,将显示以下输出。

less_parent_selectors.html