Skip to content

Less - 注释

注释 (Comments) 对于使代码易于理解和维护至关重要。LESS 支持两种类型的注释,类似于 JavaScript 和其他 C 家族语言:

  • 块级注释 (Block Comments): 这些注释以 / 开头,以 / 结尾。它们可以跨多行。块级注释在编译后会保留,并会出现在编译生成的 CSS 输出中。
  • 内联注释 (Inline / Single-Line Comments): 这些注释以 // 开头,并持续到行尾。内联注释在编译过程中会被丢弃,不会出现在最终的 CSS 文件中。这使得它们非常适合用于那些不针对最终用户或生产环境 CSS 的开发者注释。

以下示例演示了在 LESS 文件中如何使用两种注释类型,以及它们在编译过程中如何处理。

HTML 文件 (comments_example.html):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LESS Comments Example</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Demonstrating LESS Comments</h1>
<p class="main-text">This paragraph will be styled with the primary color.</p>
<p class="highlight-text">This paragraph uses a highlighted style.</p>
</body>
</html>

LESS 文件 (style.less):

/*
style.less
这是一个文件顶部的块级注释。
它将包含在编译后的 CSS 中。
*/
@primary-color: #3498db;
@highlight-color: #e74c3c;
// 定义段落的基础样式
// 此注释将不会出现在 style.css 中
.main-text {
color: @primary-color;
font-weight: bold;
/* 另一个块级注释,位于规则集内部。此注释也会被保留。 */
}
.highlight-text {
// 应用高亮颜色
color: @highlight-color;
border: 1px solid darken(@highlight-color, 10%); // 使用 LESS 函数
}

要将 style.less 编译 (compile) 成 style.css,你通常会在终端中使用 LESS 编译器 (compiler) 执行以下命令:

lessc style.less style.css

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

/*
style.less
This is a block comment at the top of the file.
It will be included in the compiled CSS.
*/
.main-text {
color: #3498db;
font-weight: bold;
/* Another block comment, inside a ruleset. This will also be preserved. */
}
.highlight-text {
color: #e74c3c;
border: 1px solid #d62c1a;
}

要查看其工作原理:

  • 将 HTML 代码保存为 comments_example.html。
  • 将 LESS 代码保存到同一目录中的 style.less。
  • 使用命令 lessc style.less style.css 将 style.less 编译到 style.css。
  • 在 Web 浏览器中打开 comments_example.html。你将看到样式已应用,如果你检查 style.css,你会注意到只有块级注释 (/* … */) 存在,而内联注释 (// …) 已被移除。

这种行为允许开发者在他们的 LESS 文件中保留详细的注释和解释,而不会增加生产环境 CSS 的文件体积。