LESS - 更改选择器顺序
说明
当选择器顺序发生更改时,将选择器添加到继承(父)选择器之前很有用。这可以通过在选择器后放置 & 来实现。例如,当您使用 Modernizer 时,您可能希望根据支持的功能指定不同的规则。
示例
以下示例演示了在 LESS 文件中使用更改选择器顺序 −
<html>
<head>
<link rel = "stylesheet" href = "changing_selector_order.css" type = "text/css" />
<title>Parent Selector</title>
</head>
<body>
<div class = "header">
<div class = "menu">
<h2>Welcome to TutorialsPoint</h2>
<p>It is possible to reference the parent selector by using &(ampersand) operator.</p>
</div>
</div>
</body>
</html>
现在,创建 style.less 文件。
style.less
.header {
.menu {
border-radius: 5px;
border: 1px solid red;
& {
padding-left: 200px;
}
}
}
您可以使用以下命令将 style.less 文件编译为 style.css −
lessc style.less style.css
执行上述命令;它将使用以下代码自动创建 style.css 文件 −
style.css
.header .menu {
border-radius: 5px;
border: 1px solid red;
padding-left: 200px;
}
.no-borderradius & 选择器会将 .no-borderradius 添加到其父选择器 .header .menu
输出
按照以下步骤查看上述代码的工作原理 −
将上述 html 代码保存在 changing_selector_order.htm 文件中。
在浏览器中打开此 HTML 文件,将显示以下输出。

less_parent_selectors.html