You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tailwind工具类的calc()中使用自定义间距变量?

在Tailwind CSS v4.1的calc()表达式中使用自定义间距变量的正确方式

你遇到的问题是因为在动态工具类的calc表达式中,直接写自定义间距名称(如my-custom-height-2)时,Tailwind不会自动将其解析为你定义的主题变量值。以下是两种可行的解决方法:

方法1:直接引用CSS自定义属性

通过@theme定义的间距变量会生成对应的CSS自定义属性(格式为--spacing-你的变量名),你可以在calc中用var()直接引用:

<div class="size-my-custom-height bg-green-800">
  <div class="size-[calc(100%-var(--spacing-my-custom-height-2))] bg-green-600"></div>
</div>

方法2:使用Tailwind的theme()函数引用主题值

Tailwind v4支持在动态工具类的calc表达式中直接调用theme()函数,传入主题路径即可获取对应的值:

<div class="size-my-custom-height bg-green-800">
  <div class="size-[calc(100%-theme(spacing.my-custom-height-2))] bg-green-600"></div>
</div>

这两种方式都能正确解析你定义的--spacing-my-custom-height-2变量值,实现预期的尺寸计算效果。

内容的提问来源于stack exchange,提问作者DevWebTk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 10:32:09