函数库详解
2025年3月5日大约 11 分钟
LESS函数库详解
LESS提供了丰富的内置函数,可以处理颜色、数学计算、字符串操作等多种任务。本文将详细介绍LESS的函数库,并提供实用示例。
字符串函数
LESS提供了多种处理字符串的函数:
@escaped: escape("a=1");
// 结果: a%3D1
@unescaped: e("a=1");
// 结果: a=1
@replaced: replace("Hello, Mars", "Mars", "World");
// 结果: Hello, World
常用字符串函数
函数名 | 描述 | 示例 |
---|---|---|
escape(string) | 对字符串进行URL编码 | escape("a=1") → a%3D1 |
e(string) | 对字符串进行转义 | e("@{color}") → 变量值 |
% | 格式化字符串 | %(\"Hello %s!\", "World") → "Hello World!" |
replace(string, pattern, replacement) | 替换字符串中的文本 | replace("Hello, Mars", "Mars", "World") → "Hello, World" |
高级字符串操作
// 字符串插值
@base-url: "http://example.com";
@path: "images/logo.png";
@image-url: "@{base-url}/@{path}";
// 结果: "http://example.com/images/logo.png"
// 格式化字符串
@format: %("RGB(%d, %d, %d)", 255, 100, 0);
// 结果: "RGB(255, 100, 0)"
// 多重替换
@text: replace("Hello Planet", "Planet", "World");
@final: replace(@text, "Hello", "Hi");
// 结果: "Hi World"
列表函数
LESS提供了处理列表的函数:
@list: "a", "b", "c";
@length: length(@list); // 结果: 3
@item: extract(@list, 2); // 结果: "b"
常用列表函数
函数名 | 描述 | 示例 |
---|---|---|
length(list) | 返回列表中的项目数量 | length(1px solid #000) → 3 |
extract(list, index) | 返回列表中指定位置的项目 | extract(8px 16px 24px, 2) → 16px |
列表操作示例
// 定义边框样式列表
@borders: 1px solid #ccc, 2px dashed #999, 3px dotted #333;
// 获取列表长度
@border-count: length(@borders); // 结果: 3
// 提取特定项目
@second-border: extract(@borders, 2); // 结果: 2px dashed #999
// 在混合中使用列表函数
.apply-nth-border(@list, @n) {
border: extract(@list, @n);
}
.box {
.apply-nth-border(@borders, 1); // 应用第一种边框样式
}
.card {
.apply-nth-border(@borders, 3); // 应用第三种边框样式
}
数学函数
LESS提供了丰富的数学函数,用于各种数值计算。
基本数学函数
函数名 | 描述 | 示例 |
---|---|---|
ceil(number) | 向上取整 | ceil(2.4) → 3 |
floor(number) | 向下取整 | floor(2.6) → 2 |
round(number) | 四舍五入 | round(2.5) → 3 |
abs(number) | 绝对值 | abs(-5) → 5 |
高级数学函数
函数名 | 描述 | 示例 |
---|---|---|
min(a, b, ...) | 返回最小值 | min(5, 10, 3) → 3 |
max(a, b, ...) | 返回最大值 | max(5, 10, 3) → 10 |
percentage(number) | 将数字转换为百分比 | percentage(0.5) → 50% |
pi() | 返回π值 | pi() → 3.141592653589793 |
pow(base, exponent) | 计算幂 | pow(2, 3) → 8 |
sqrt(number) | 计算平方根 | sqrt(25) → 5 |
sin(number) | 正弦函数 | sin(pi()/2) → 1 |
cos(number) | 余弦函数 | cos(0) → 1 |
tan(number) | 正切函数 | tan(0) → 0 |
数学函数示例
// 基本计算
@width: 100px;
@height: 50px;
@area: @width * @height; // 结果: 5000px²
// 使用数学函数
@value: 3.7;
@rounded: round(@value); // 结果: 4
@floored: floor(@value); // 结果: 3
@ceiled: ceil(@value); // 结果: 4
// 响应式计算
@container-width: 1200px;
@column-count: 12;
@gutter: 20px;
@column-width: (@container-width - (@column-count - 1) * @gutter) / @column-count;
// 结果: 81.67px
// 百分比计算
.col-6 {
width: percentage(6 / @column-count); // 结果: 50%
}
// 最大值和最小值
@responsive-font: max(12px, min(16px, 1.5vw));
颜色函数
LESS提供了强大的颜色操作函数,可以动态调整颜色。
颜色信息函数
函数名 | 描述 | 示例 |
---|---|---|
rgb(r, g, b) | 创建RGB颜色 | rgb(255, 0, 0) → #ff0000 |
rgba(r, g, b, a) | 创建带透明度的RGB颜色 | rgba(255, 0, 0, 0.5) → rgba(255, 0, 0, 0.5) |
argb(color) | 返回颜色的ARGB十六进制表示 | argb(rgba(255, 0, 0, 0.5)) → #80ff0000 |
hsl(h, s, l) | 创建HSL颜色 | hsl(0, 100%, 50%) → #ff0000 |
hsla(h, s, l, a) | 创建带透明度的HSL颜色 | hsla(0, 100%, 50%, 0.5) → rgba(255, 0, 0, 0.5) |
hue(color) | 提取颜色的色相 | hue(#ff0000) → 0 |
saturation(color) | 提取颜色的饱和度 | saturation(#ff0000) → 100% |
lightness(color) | 提取颜色的亮度 | lightness(#ff0000) → 50% |
alpha(color) | 提取颜色的透明度 | alpha(rgba(255, 0, 0, 0.5)) → 0.5 |
red(color) | 提取颜色的红色通道 | red(#ff0000) → 255 |
green(color) | 提取颜色的绿色通道 | green(#00ff00) → 255 |
blue(color) | 提取颜色的蓝色通道 | blue(#0000ff) → 255 |
颜色操作函数
函数名 | 描述 | 示例 |
---|---|---|
lighten(color, amount) | 增加颜色亮度 | lighten(#007bff, 10%) → #3395ff |
darken(color, amount) | 降低颜色亮度 | darken(#007bff, 10%) → #0062cc |
saturate(color, amount) | 增加颜色饱和度 | saturate(#0e6ac7, 20%) → #0057c7 |
desaturate(color, amount) | 降低颜色饱和度 | desaturate(#0e6ac7, 20%) → #247eb7 |
fadein(color, amount) | 增加颜色不透明度 | fadein(rgba(0, 0, 0, 0.5), 10%) → rgba(0, 0, 0, 0.6) |
fadeout(color, amount) | 降低颜色不透明度 | fadeout(rgba(0, 0, 0, 0.5), 10%) → rgba(0, 0, 0, 0.4) |
fade(color, amount) | 设置颜色透明度 | fade(#007bff, 50%) → rgba(0, 123, 255, 0.5) |
spin(color, angle) | 旋转颜色色相 | spin(#007bff, 180) → #ff7b00 |
mix(color1, color2, weight) | 混合两种颜色 | mix(#ff0000, #0000ff, 50%) → #800080 |
greyscale(color) | 将颜色转换为灰度 | greyscale(#007bff) → #7b7b7b |
contrast(color, dark, light) | 根据颜色亮度选择深色或浅色 | contrast(#007bff, black, white) → white |
颜色函数示例
// 定义基础颜色
@primary: #007bff;
@success: #28a745;
@danger: #dc3545;
// 创建颜色变体
@primary-light: lighten(@primary, 15%); // 结果: #4dabff
@primary-dark: darken(@primary, 15%); // 结果: #004a99
// 创建悬停效果
.button {
background-color: @primary;
&:hover {
background-color: darken(@primary, 10%);
}
&:active {
background-color: darken(@primary, 15%);
}
}
// 创建透明变体
@primary-transparent: fade(@primary, 50%); // 结果: rgba(0, 123, 255, 0.5)
// 创建互补色
@primary-complement: spin(@primary, 180); // 结果: #ff7b00
// 创建配色方案
@triad-1: spin(@primary, 120); // 结果: #00ff7b
@triad-2: spin(@primary, 240); // 结果: #7b00ff
// 基于亮度选择文本颜色
.dynamic-text(@bg-color) {
background-color: @bg-color;
color: contrast(@bg-color, #000, #fff);
}
.primary-box {
.dynamic-text(@primary); // 文本颜色将是白色
}
.light-box {
.dynamic-text(#f8f9fa); // 文本颜色将是黑色
}
类型函数
LESS提供了检查和操作变量类型的函数。
类型检查函数
函数名 | 描述 | 示例 |
---|---|---|
isnumber(value) | 检查值是否为数字 | isnumber(123) → true |
isstring(value) | 检查值是否为字符串 | isstring("abc") → true |
iscolor(value) | 检查值是否为颜色 | iscolor(#ff0000) → true |
iskeyword(value) | 检查值是否为关键字 | iskeyword(keyword) → true |
isurl(value) | 检查值是否为URL | isurl(url("http://example.com")) → true |
ispixel(value) | 检查值是否为像素单位 | ispixel(10px) → true |
isem(value) | 检查值是否为em单位 | isem(2em) → true |
ispercentage(value) | 检查值是否为百分比 | ispercentage(50%) → true |
isunit(value, unit) | 检查值是否为指定单位 | isunit(10px, "px") → true |
isruleset(value) | 检查值是否为规则集 | isruleset(@rules) → true/false |
类型函数示例
// 定义混合,根据参数类型应用不同样式
.set-width(@value) when (isnumber(@value)) {
width: @value;
}
.set-width(@value) when (ispercentage(@value)) {
max-width: @value;
}
.set-width(@value) when (isstring(@value)) {
width: e(@value);
}
// 使用混合
.box-1 {
.set-width(300px); // 设置固定宽度
}
.box-2 {
.set-width(50%); // 设置最大宽度
}
.box-3 {
.set-width("calc(100% - 20px)"); // 设置计算值
}
// 条件混合中使用类型检查
.responsive-style(@value) when (ispixel(@value)) {
@media (max-width: 768px) {
padding: @value / 2;
}
}
.responsive-style(@value) when (ispercentage(@value)) {
@media (max-width: 768px) {
width: @value - 10%;
}
}
.container {
padding: 20px;
width: 80%;
.responsive-style(20px);
.responsive-style(80%);
}
杂项函数
LESS提供了一些不属于上述类别的实用函数。
单位操作函数
函数名 | 描述 | 示例 |
---|---|---|
unit(number, unit) | 更改或添加单位 | unit(5, "px") → 5px |
unit(dimension) | 移除单位 | unit(5px) → 5 |
get-unit(number) | 返回数字的单位 | get-unit(5px) → "px" |
convert(number, unit) | 转换单位 | convert(1in, "px") → 96px |
其他实用函数
函数名 | 描述 | 示例 |
---|---|---|
color(string) | 将字符串转换为颜色 | color("#ff0000") → #ff0000 |
data-uri(mimetype, url) | 将资源内联为data URI | data-uri('image/jpeg', 'image.jpg') |
default() | 仅当变量未定义时使用默认值 | @width: default(@var, 100px) |
if(condition, value1, value2) | 条件表达式 | if(true, 1px, 2px) → 1px |
杂项函数示例
// 单位操作
@size: 16;
@pixel-size: unit(@size, "px"); // 结果: 16px
@unitless: unit(@pixel-size); // 结果: 16
@unit-type: get-unit(@pixel-size); // 结果: "px"
// 单位转换
@inches: 1in;
@pixels: convert(@inches, "px"); // 结果: 96px
// 条件表达式
@is-mobile: true;
@padding: if(@is-mobile, 10px, 20px); // 结果: 10px
// 默认值
@custom-width: 200px;
.element {
width: default(@custom-width, 100px); // 结果: 200px
}
// 未定义变量的情况
.another-element {
width: default(@undefined-var, 100px); // 结果: 100px
}
// 内联资源
.logo {
background-image: data-uri('image/svg+xml;charset=UTF-8', 'logo.svg');
}
命名空间和作用域函数
LESS提供了处理命名空间和变量作用域的函数。
命名空间函数
函数名 | 描述 | 示例 |
---|---|---|
@import-once | 确保文件只被导入一次 | @import-once "file.less"; |
@import (reference) | 导入但不输出 | @import (reference) "mixins.less"; |
作用域函数
函数名 | 描述 | 示例 |
---|---|---|
@arguments | 在混合中捕获所有参数 | .mixin(@a, @b) { margin: @arguments; } |
@rest | 捕获剩余参数 | .mixin(@a, @rest...) { padding: @a @rest; } |
命名空间和作用域示例
// 定义命名空间
#namespace() {
.border-radius(@radius) {
border-radius: @radius;
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
}
.box-shadow(@x, @y, @blur, @color) {
box-shadow: @arguments;
-webkit-box-shadow: @arguments;
}
}
// 使用命名空间中的混合
.button {
#namespace.border-radius(4px);
#namespace.box-shadow(0, 2px, 5px, rgba(0, 0, 0, 0.3));
}
// 使用@arguments捕获所有参数
.margin(@t, @r, @b, @l) {
margin: @arguments;
}
.padding(@a, @rest...) {
padding: @a @rest;
}
.card {
.margin(10px, 15px, 10px, 15px); // 结果: margin: 10px 15px 10px 15px;
.padding(5px, 10px, 15px); // 结果: padding: 5px 10px 15px;
}
函数组合与高级用法
LESS函数可以组合使用,创建复杂的样式逻辑。
函数组合示例
// 组合颜色函数创建渐变色板
@base-color: #3498db;
@complementary: spin(@base-color, 180);
@analogous-1: spin(@base-color, 30);
@analogous-2: spin(@base-color, -30);
@triadic-1: spin(@base-color, 120);
@triadic-2: spin(@base-color, 240);
// 组合数学和颜色函数创建明暗变体
.generate-variants(@color, @name, @steps: 5, @step-size: 10%) {
.@{name} {
color: @color;
}
.generate-variants-loop(@i: 1) when (@i <= @steps) {
.@{name}-lighter-@{i} {
color: lighten(@color, @i * @step-size);
}
.@{name}-darker-@{i} {
color: darken(@color, @i * @step-size);
}
.generate-variants-loop(@i + 1);
}
.generate-variants-loop();
}
// 应用组合函数
.generate-variants(@base-color, "primary");
.generate-variants(@complementary, "complementary", 3, 15%);
// 组合字符串和数学函数创建网格系统
.create-grid(@columns, @prefix: "col") {
.create-grid-loop(@i: 1) when (@i <= @columns) {
.@{prefix}-@{i} {
width: percentage(@i / @columns);
}
.create-grid-loop(@i + 1);
}
.create-grid-loop();
}
// 创建12列网格
.create-grid(12);
// 组合类型检查和条件函数创建响应式工具
.responsive(@property, @value, @breakpoint: 768px) when (ispixel(@value)) {
@{property}: @value;
@media (max-width: @breakpoint) {
@{property}: @value * 0.8;
}
}
.responsive(@property, @value, @breakpoint: 768px) when (ispercentage(@value)) {
@{property}: @value;
@media (max-width: @breakpoint) {
@{property}: @value - 10%;
}
}
// 应用响应式工具
.container {
.responsive(width, 960px);
.responsive(margin, 5%);
}
自定义函数
虽然LESS不支持直接定义函数,但可以使用混合和变量模拟函数行为。
模拟函数示例
// 模拟计算函数
.calc-width(@columns, @total: 12) {
@result: percentage(@columns / @total);
width: @result;
}
// 模拟颜色函数
.create-gradient-color(@base-color, @lightness-start: 20%, @lightness-end: 80%) {
@start-color: lighten(@base-color, @lightness-start);
@end-color: lighten(@base-color, @lightness-end);
background: linear-gradient(to bottom, @start-color, @end-color);
}
// 模拟字符串处理函数
.build-class(@prefix, @name) {
@result: ~"@{prefix}-@{name}";
&.@{result} {
content: "@{result}";
}
}
// 应用模拟函数
.column {
.calc-width(6); // 结果: width: 50%;
}
.button {
.create-gradient-color(#3498db); // 创建蓝色渐变
}
.element {
.build-class("theme", "dark"); // 创建 .element.theme-dark
}
函数使用最佳实践
性能优化
- 避免过度嵌套函数调用
- 使用变量存储复杂计算结果
- 对频繁使用的函数结果进行缓存
// 不推荐 - 重复计算
.element-1 {
color: darken(lighten(#3498db, 10%), 5%);
}
.element-2 {
background-color: darken(lighten(#3498db, 10%), 5%);
}
// 推荐 - 缓存计算结果
@processed-color: darken(lighten(#3498db, 10%), 5%);
.element-1 {
color: @processed-color;
}
.element-2 {
background-color: @processed-color;
}
可维护性
- 为复杂函数组合创建混合
- 使用有意义的变量名
- 添加注释解释函数的用途
// 创建可重用的函数组合
.create-text-style(@color, @size, @weight) {
// 生成对比度良好的文本样式
color: @color;
background-color: contrast(@color, white, black);
font-size: @size;
font-weight: @weight;
text-shadow: 0 1px 1px fade(contrast(@color, black, white), 20%);
}
// 应用函数组合
.primary-text {
.create-text-style(#3498db, 16px, bold);
}
.secondary-text {
.create-text-style(#2ecc71, 14px, normal);
}
调试技巧
- 使用注释输出变量值
- 创建调试混合
// 调试混合
.debug(@value) {
/* DEBUG: @{value} */
}
// 在开发中使用
@calculated-width: percentage(4/12);
.debug(@calculated-width);
.column-4 {
width: @calculated-width;
}
总结
LESS函数库提供了丰富的工具,可以处理字符串、列表、数学计算、颜色操作和类型检查等多种任务。通过组合这些函数,可以创建强大的样式系统,提高CSS的可维护性和可扩展性。
主要函数类别包括:
- 字符串函数:处理文本和字符串插值
- 列表函数:操作值列表和提取项目
- 数学函数:执行数值计算和单位转换
- 颜色函数:创建和操作颜色
- 类型函数:检查值的类型
- 杂项函数:提供其他实用功能
通过掌握这些函数,开发者可以充分利用LESS的强大功能,创建更加灵活和动态的样式表。