Skip to content

Less - 嵌套规则

嵌套 (Nesting) 是 LESS 最强大的功能之一。它允许你以一种分层结构 (hierarchical structure) 编写 CSS 选择器 (CSS selectors),这种结构反映了你的 HTML 结构。这通过减少重复和清晰地定义作用域 (scope),使你的 LESS 代码更加有组织、易读且易于维护。

你无需编写冗长且重复的选择器,而是可以将子选择器 (child selectors) 嵌套在其父选择器 (parent selectors) 内部。LESS 会处理这些嵌套规则并生成相应的标准 CSS。

LESS 包含一个特殊的选择器 &,称为父选择器。它主要用于当你想要对当前嵌套级别的父选择器应用伪类 (pseudo-class)、属性选择器 (attribute selector) 或修饰符类 (modifier class) 而无需重复其名称时。它也可以用于创建更复杂的选择器组合。

  • 伪类 (Pseudo-classes): a { &:hover { … } } 编译为 a:hover { … }。
  • 父元素上的修饰符类 (Modifier classes on the parent): .button { &.large { … } } 编译为 .button.large { … }。
  • 前置选择器 (Prepending selectors): 在 .element 的嵌套规则内使用 body.theme-dark & { … } 将编译为 body.theme-dark .element { … }。

以下示例演示了嵌套规则,包括父选择器 & 的使用。

HTML 文件 (nested_rules_example.html):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LESS Nested Rules Example</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header class="main-header">
<h1>Site Title</h1>
<nav>
<ul>
<li><a href="#" class="active">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
<div class="content">
<p>This is some primary content.</p>
<div class="sidebar">
<p>This is a sidebar section.</p>
</div>
</div>
</body>
</html>

LESS 文件 (style.less):

.main-header {
background-color: #f0f0f0;
padding: 20px;
h1 {
margin: 0 0 15px 0;
color: #333;
}
nav {
ul {
list-style: none;
padding: 0;
margin: 0;
li {
display: inline-block;
margin-right: 10px;
a {
text-decoration: none;
color: #007bff;
&:hover {
text-decoration: underline;
}
&.active {
font-weight: bold;
color: #0056b3;
}
}
}
}
}
}
.content {
padding: 15px;
p {
font-size: 16px;
line-height: 1.6;
}
// 嵌套子选择器
.sidebar {
background-color: #e9ecef;
padding: 10px;
margin-top: 15px;
p {
font-size: 14px;
color: #555;
}
}
}

将 style.less 编译到 style.css:

lessc style.less style.css

编译后的 CSS 文件 (style.css):

.main-header {
background-color: #f0f0f0;
padding: 20px;
}
.main-header h1 {
margin: 0 0 15px 0;
color: #333;
}
.main-header nav ul {
list-style: none;
padding: 0;
margin: 0;
}
.main-header nav ul li {
display: inline-block;
margin-right: 10px;
}
.main-header nav ul li a {
text-decoration: none;
color: #007bff;
}
.main-header nav ul li a:hover {
text-decoration: underline;
}
.main-header nav ul li a.active {
font-weight: bold;
color: #0056b3;
}
.content {
padding: 15px;
}
.content p {
font-size: 16px;
line-height: 1.6;
}
.content .sidebar {
background-color: #e9ecef;
padding: 10px;
margin-top: 15px;
}
.content .sidebar p {
font-size: 14px;
color: #555;
}

要观察效果:

  • 将 HTML 代码保存为 nested_rules_example.html。
  • 将 LESS 代码保存为 style.less。
  • 将其编译到 style.css。
  • 在浏览器中打开 nested_rules_example.html。通过嵌套定义的样式将被应用。

嵌套规则显著提高了复杂样式表 (stylesheets) 的组织性。然而,最好避免过度嵌套(超过 3-4 层),因为它可能导致过于具体的 CSS 选择器,难以覆盖 (override) 且可能影响性能 (impact performance)。(有关嵌套策略的更多信息,请参阅官方 Less 文档:lesscss.org/features/#features-overview-feature-nested-rules)