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

如何使用Tailwind修改CSS自定义变量?

解决Tailwind hover状态下修改CSS变量的问题

方法一:自定义全局工具类(推荐)

在全局CSS文件(如index.css)中,借助Tailwind的@layer utilities定义带hover状态的工具类,确保类会被Tailwind构建流程识别,不会被误删:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer utilities {
  /* 定义hover/focus时修改--property变量的类 */
  .hover-focus-update-property {
    &:hover,
    &:focus {
      --property: 1.1;
    }
  }
}

在组件中直接使用该类即可:

<div className='hover-focus-update-property'>
  <img className='scale-x-[var(--property)]' src="..." />
</div>

方法二:在tailwind.config.js中扩展工具类

如果想要直接用Tailwind的hover:前缀语法,可在配置文件中自定义工具类并启用对应变体:

// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      utilities: {
        'set-property-1_1': {
          '--property': '1.1',
        },
      },
    },
  },
  variants: {
    extend: {
      utilities: ['hover', 'focus'],
    },
  },
}

之后通过hover变体调用工具类:

<div className='hover:set-property-1_1 focus:set-property-1_1'>
  <img className='scale-x-[var(--property)]' src="..." />
</div>

注意事项

  • 你之前的scale-x-[var(--property]存在语法错误,需补上闭合括号,正确写法为scale-x-[var(--property)]
  • 若变量值包含小数点,可在类名中用下划线替代,避免解析异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:27:27