Skip to content

Less - 函数

LESS 提供了一组丰富的内置函数,允许你在样式表中直接操作值。这些函数对于创建动态、可维护和复杂的样式非常宝贵。它们涵盖了各种类别,包括:

  • 数学函数: 用于执行计算(例如,round(),ceil(),floor(),sqrt(),abs())。
  • 字符串函数: 用于操作文本(例如,escape(),replace(),e(),format())。
  • 颜色函数: 用于转换颜色(例如,lighten(),darken(),saturate(),mix(),rgba())。
  • 列表函数: 用于处理逗号或空格分隔的值列表(例如,length(),extract())。
  • 类型函数: 用于检查值的数据类型(例如,isnumber(),iscolor())。详见“类型函数”章节。
  • 杂项函数: 包括将无单位数字转换为百分比的 percentage(),更改或添加单位的 unit(),以及更多。

这些函数有助于保持你的 LESS 代码 DRY(Don’t Repeat Yourself,不要重复自己),并使复杂的计算或转换变得可读且易于管理。

以下示例演示了 percentage() 函数的使用,该函数将无单位数字(解释为比率,例如 0.5 表示 50%)转换为百分比值。

创建一个名为 functions_example.html 的 HTML 文件:

Section titled “创建一个名为 functions_example.html 的 HTML 文件:”
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LESS Functions Example</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h1>Example using Functions</h1>
<p class="my-element">LESS enables customizable, manageable, and reusable stylesheets for websites. This paragraph's width is set using the percentage() function.</p>
</body>
</html>

创建名为 style.less 的 LESS 文件:

Section titled “创建名为 style.less 的 LESS 文件:”
@base-color: #007bff; // A nice blue
@container-proportion: 0.8; // Represents 80%
.my-element {
color: @base-color;
background-color: lighten(@base-color, 30%); // Using a color function
width: percentage(@container-proportion); // Using the percentage() function
padding: round(15.7px); // Using a math function
font-family: e("Arial, sans-serif"); // Using e() for unquoted string
}

要将 style.less 编译为 style.css,通常可以使用通过 Node.js/npm 安装的 LESS 编译器:

首先,确保你已安装 Node.js 和 npm。然后,全局安装 LESS 编译器(或作为项目依赖):
npm install -g less
然后,编译你的文件:
lessc style.less style.css
.my-element {
color: #007bff;
background-color: #99ccff; /* lighten(#007bff, 30%) 的结果 */
width: 80%; /* percentage(0.8) 的结果 */
padding: 16px; /* round(15.7px) 的结果 */
font-family: Arial, sans-serif; /* e("Arial, sans-serif") 的结果 */
}

在 Web 浏览器中打开 functions_example.html 时:

  • 主标题“Example using Functions”将被显示。
  • 带有类名 my-element 的段落文本将是蓝色(#007bff)。
  • 其背景将是浅蓝色(#99ccff)。
  • 其宽度将是其包含块的 80%。
  • 其内边距(padding)将是 16px。
  • 其字体将是 Arial 或通用的 sans-serif 字体。

这演示了 LESS 函数如何动态生成 CSS 值,从而生成更灵活、更易于维护的样式表。