SASS 内置模块
本文介绍 SASS 的内置模块。
我们将从基础到高级用法,循序渐进地讲解 SASS 的内置模块。
YouTube Video
SASS 内置模块
SASS 提供了多种内置模块,使用它们可以让样式表编写更加高效。
什么是 SASS 的内置模块?
SASS 的内置模块是提供可复用函数和 mixin(混入)的模块。使用它们可以更轻松地进行复杂计算并创建自定义样式。
主要的内置模块包括:。
sass:colorsass:stringsass:mathsass:listsass:mapsass:selectorsass:meta
每个模块都包含用于简化特定任务的功能。
各模块的详细说明与示例
sass:color 模块
sass:color 模块提供了便于进行颜色操作的函数。
主要函数
mix(): 混合两种颜色adjust(): 同时调整色相、亮度、饱和度等属性
用法示例
1@use "sass:color";
2
3$primary-color: #3498db;
4$secondary-color: #e74c3c;
5
6// Mix two colors with equal weight
7$blended-color: color.mix($primary-color, $secondary-color, 50%);
8
9// Adjust hue by 45 degrees using color.adjust()
10$adjusted-color: color.adjust($primary-color, $hue: 45deg);
11
12div {
13 background-color: $blended-color; // Result of mixing two colors
14 border-color: $adjusted-color; // Hue adjusted by 45 degrees
15}- 该代码通过混合两种颜色生成一种新颜色,并生成另一种色相已调整的颜色。生成的颜色被应用为元素的背景色和边框色。这个示例有助于你理解颜色操作的基础。
sass:string 模块
sass:string 模块提供了对字符串操作有用的函数。
主要函数
quote(),unquote(): 为字符串加引号或去引号length(): 获取字符串长度to-upper-case(),to-lower-case(): 将字符串转换为大写或小写
用法示例
1@use "sass:string";
2
3// base values
4$base-url: "https://example.com";
5$path: "/assets/style.css";
6
7// 1) Combine strings using interpolation and then quote the result
8$full-quoted: string.quote("#{$base-url}#{$path}");
9// Example result: "\"https://example.com/assets/style.css\""
10
11// 2) Remove quotes from a quoted string
12$full-unquoted: string.unquote($full-quoted);
13// Example result: https://example.com/assets/style.css
14
15// 3) Get the length of the unquoted string
16$url-length: string.length($full-unquoted);
17// Example output: number of characters in the URL
18
19// 4) Convert strings to upper/lower case and quote for safe CSS output
20$block-name: "main-header";
21// "MAIN-HEADER"
22$upper-quoted: string.quote(string.to-upper-case($block-name));
23// "main-footer"
24$lower-quoted: string.quote(string.to-lower-case("MAIN-FOOTER"));
25
26a::after {
27 /* Use quoted strings for content to ensure valid CSS */
28 content: $full-quoted; /* "https://example.com/assets/style.css" */
29}
30
31:root {
32 /* Insert numeric values with interpolation when needed */
33 --url-length: #{ $url-length }; /* Example: --url-length: 31; */
34}
35
36.header::before {
37 /* Output uppercase version */
38 content: $upper-quoted; /* "MAIN-HEADER" */
39}
40
41.footer::after {
42 /* Output lowercase version */
43 content: $lower-quoted; /* "main-footer" */
44}- 使用
string.quote()和string.unquote()可以精确控制输出 CSS 中字符串的表现形式。string.length()是获取字符串长度的函数。string.to-upper-case()/string.to-lower-case()有助于生成类名并格式化 BEM 名称。
sass:math 模块
sass:math 模块提供用于数学计算的函数。
主要函数
pow(): 幂运算sqrt(): 平方根abs(): 绝对值round(),ceil(),floor(): 四舍五入、向上取整、向下取整
用法示例
1@use "sass:math";
2
3// Using pow() to calculate exponential values
4$base-size: math.pow(2, 3) * 10px; // 80px
5
6// Using sqrt() to compute a square root
7$root-size: math.sqrt(144) * 1px; // 12px
8
9// Using abs() to ensure a positive value
10$offset: math.abs(-15px); // 15px
11
12// Using round(), ceil(), and floor() for different rounding methods
13$rounded: math.round(12.6px); // 13px
14$ceiled: math.ceil(12.1px); // 13px
15$floored: math.floor(12.9px); // 12px
16
17.container {
18 width: $base-size; // 80px
19 height: $root-size; // 12px
20 margin-left: $offset; // 15px
21}
22
23.values {
24 /* Demonstrating different rounding operations */
25 padding: $rounded; // 13px
26 border-width: $ceiled; // 13px
27 margin-top: $floored; // 12px
28}math.pow()和math.sqrt()有助于尺寸计算,而math.abs()及取整函数有助于处理调整。组合使用这些函数可以轻松计算统一的 UI 比例体系。
sass:list 模块
sass:list 模块提供专门用于列表操作的函数。
主要函数
append(): 添加元素join(): 合并列表nth(): 获取指定位置的元素length(): 获取列表长度
用法示例
1@use "sass:list";
2
3// Base list
4$colors: ("red", "blue", "green");
5
6// Add an element to the end of the list
7$colors-appended: list.append($colors, "yellow");
8// ("red", "blue", "green", "yellow")
9
10// Add an element to the beginning of the list using join()
11$colors-prepended: list.join(("black",), $colors);
12// ("black", "red", "blue", "green", "yellow")
13
14// Join two lists together
15$extra-colors: ("pink", "cyan");
16$merged-colors: list.join($colors-prepended, $extra-colors);
17// ("black", "red", "blue", "green", "yellow", "pink", "cyan")
18
19// Get list length
20$total-length: list.length($merged-colors);
21
22// Example usage in a loop: assign each color to a list item
23ul {
24 @for $i from 1 through $total-length {
25 li:nth-child(#{$i}) {
26 /* Get the color at index $i */
27 color: list.nth($merged-colors, $i);
28 }
29 }
30}- 你可以用
append()向列表末尾添加元素,并用join()灵活地合并多个列表。如果你想在开头添加元素,可以用join()将包含一个元素的列表连接到前面。结合使用length()和nth(),可以更容易地生成需要动态列表处理的 UI 样式。
sass:map 模块
sass:map 模块提供用于处理映射(关联数组)的函数。
主要函数
get(): 获取键对应的值set(): 添加或更新键值对keys(): 获取所有键
用法示例
1@use "sass:map";
2
3// Base theme map
4$theme-colors: (
5 "primary": #3498db,
6 "secondary": #e74c3c
7);
8
9// Update or add a value using set()
10$updated-theme: map.set($theme-colors, "warning", #f1c40f);
11// Map now has "warning": #f1c40f added
12
13// Get a value from the map
14$primary-color: map.get($updated-theme, "primary");
15
16// Get all keys from the map
17$all-keys: map.keys($updated-theme);
18// Example: ("primary", "secondary", "warning")
19
20button {
21 /* Apply color retrieved from the theme map */
22 background-color: $primary-color;
23}
24
25.debug {
26 /* Print keys as content for demonstration */
27 content: "#{$all-keys}";
28}- 使用
map.set()可以动态更新映射,配合map.get()能构建灵活的主题结构。通过map.keys()可以列出配置项,有助于设计可扩展的样式。
sass:selector 模块
sass:selector 模块提供对选择器操作有帮助的函数。
主要函数
nest(): 嵌套选择器is-superselector(): 检查选择器包含关系replace(): 替换选择器
用法示例
1@use "sass:selector";
2
3// Nest selectors (combine parent and child)
4$nested-selector: selector.nest(".parent", ".child");
5// Result: ".parent .child"
6
7// Check if one selector is a superselector of another
8$is-super: selector.is-superselector(".parent", $nested-selector);
9// true because ".parent" matches all elements that
10// ".parent .child" can match as an ancestor
11
12// Replace part of a selector with another selector
13$replaced-selector: selector.replace(".parent .child", ".child", ".item");
14// Result: ".parent .item"
15
16// Use generated selectors in actual CSS output
17#{$nested-selector} {
18 /* Applies to .parent .child */
19 color: red;
20}
21
22@if $is-super {
23 .info::after {
24 /* Demonstrate boolean result */
25 content: "parent is a superselector";
26 }
27}
28
29#{$replaced-selector} {
30 /* Applies to .parent .item */
31 background: blue;
32}- 使用
selector.nest()可灵活组合选择器,使用selector.is-superselector()可验证它们之间的关系。结合selector.replace()可简洁地处理高级选择器生成逻辑。
sass:meta 模块
sass:meta 模块提供对 SASS 中元编程有用的特性。
主要函数
variable-exists(): 检查变量是否存在global-variable-exists(): 检查全局变量是否存在inspect(): 输出用于调试的值
用法示例
1@use "sass:meta";
2
3// Define a global variable
4$color: #3498db;
5
6// Check if a variable exists in the current scope
7@if meta.variable-exists("color") {
8 body {
9 /* Apply style only if $color exists */
10 background-color: $color;
11 }
12}
13
14// Create a local variable inside a block
15.container {
16 $local-size: 20px;
17
18 @if meta.variable-exists("local-size") {
19 /* Demonstrates detection of local variable */
20 width: $local-size;
21 }
22}
23
24// Check if a global variable exists
25$result: meta.global-variable-exists("color"); // true
26
27.debug {
28 /* Use inspect() to output the inspected value as a string */
29 content: meta.inspect($result); // "true"
30}meta.variable-exists()和meta.global-variable-exists()可按作用域安全地判断变量状态。meta.inspect()对调试非常有用,并可将值以字符串形式显示。
实用示例
组合多个内置模块可进一步增强 SASS 的表达力。下面的示例同时使用 color、math 和 list 模块,以实现颜色处理和列表操作的自动化。
1@use "sass:color";
2@use "sass:math";
3@use "sass:list";
4
5// Base color list
6$base-colors: (#3498db, #e74c3c, #2ecc71);
7$darkened-colors: (); // Empty list for processed colors
8
9// Loop through each base color and darken it by 10%
10@each $color in $base-colors {
11 $darkened-colors: list.append(
12 $darkened-colors,
13 // Darken color by decreasing lightness by 10%
14 color.adjust($color, $lightness: -10%)
15 );
16}
17
18div {
19 // Apply each processed color to a corresponding <div>
20 @for $i from 1 through list.length($darkened-colors) {
21 &:nth-child(#{$i}) {
22 // Set color by index
23 background-color: list.nth($darkened-colors, $i);
24 }
25 }
26}- 在此代码中,处理后的颜色通过
list.append()依次添加,并通过color.adjust()的$lightness: -10%使颜色变暗 10%。最后,将@for与list.nth()结合,为每个<div>应用不同的背景色。
总结
SASS 的内置模块极大提升了 CSS 的灵活性。通过理解各模块并恰当使用,你可以编写更高效且更易维护的样式表。
您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。