Sass Variable in CSS calc() function

Sass Variable in CSS calc() function

技术背景

在CSS中,calc() 函数用于进行简单的数学计算,而Sass作为CSS预处理器,提供了变量等强大功能。将Sass变量应用于CSS的 calc() 函数中,可以让样式的计算更加灵活和可维护。

实现步骤

1. 使用插值语法

在Sass中,可以使用插值 #{$variable} 的方式将变量嵌入到 calc() 函数中。例如:

1
2
3
4
$body_padding: 20px;
body {
height: calc(100% - #{$body_padding});
}

2. 注意空格问题

calc() 函数中,运算符前后需要有适当的空格,否则可能导致计算不生效。例如:

1
2
3
4
5
6
7
8
9
$a: 4em;
// 错误示例
div {
height: calc(#{$a}+7px); // 此代码可能不生效
}
// 正确示例
div {
height: calc(#{$a} + 7px);
}

3. 利用Sass变量进行媒体查询计算

可以通过Sass变量和 calc() 函数结合,实现根据不同媒体断点自动计算尺寸。示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
$base-size: 16;
$rate-size-xl: 24;

// set default size for all cases;
:root {
--size: #{$base-size};
}

// if it's smaller then LG it will set size rate to 16/16;
// example: if size set to 14px, it will be 14px * 16 / 16 = 14px
@include media-breakpoint-down(lg) {
:root {
--size: #{$base-size};
}
}

// if it is bigger then XL it will set size rate to 24/16;
// example: if size set to 14px, it will be 14px * 24 / 16 = 21px
@include media-breakpoint-up(xl) {
:root {
--size: #{$rate-size-xl};
}
}

@function size($px) {
@return calc(#{$px} / $base-size * var(--size));
}

div {
font-size: size(14px);
width: size(150px);
}

4. 创建混合器

可以创建Sass混合器来复用包含 calc() 函数的样式。示例如下:

1
2
3
4
5
6
7
8
9
@mixin heightBox($body_padding){
height: calc(100% - $body_padding);
}

body{
@include heightBox(100% - 25%);
box-sizing: border-box;
padding:10px;
}

核心代码

基本使用

1
2
3
4
5
$a: 4em;
div {
height: calc(#{$a} + 7px);
background: #e53b2c;
}

媒体查询计算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$base-size: 16;
$rate-size-xl: 24;

:root {
--size: #{$base-size};
}

@include media-breakpoint-down(lg) {
:root {
--size: #{$base-size};
}
}

@include media-breakpoint-up(xl) {
:root {
--size: #{$rate-size-xl};
}
}

@function size($px) {
@return calc(#{$px} / $base-size * var(--size));
}

div {
font-size: size(14px);
width: size(150px);
}

混合器使用

1
2
3
4
5
6
7
8
9
@mixin heightBox($body_padding){
height: calc(100% - $body_padding);
}

body{
@include heightBox(100% - 25%);
box-sizing: border-box;
padding:10px;
}

最佳实践

  • 合理使用变量:将常用的尺寸、颜色等定义为Sass变量,方便在 calc() 函数中复用和修改。
  • 注意兼容性:确保浏览器支持 calc() 函数和Sass编译后的CSS语法。
  • 代码复用:通过创建混合器和函数,减少重复代码,提高代码的可维护性。

常见问题

  • 计算不生效:检查 calc() 函数中运算符前后是否有适当的空格。
  • 变量未生效:确认变量是否正确定义和使用插值语法 #{$variable}

Sass Variable in CSS calc() function
https://119291.xyz/posts/sass-variable-in-css-calc-function/
作者
ww
发布于
2025年5月26日
许可协议