如何为Tailwind Typography插件主题扩展颜色及颜色透明度
解决Tailwind Typography中为背景色添加内置颜色及透明度的问题
在Tailwind配置的theme()函数里,不能直接用类名中的/透明度语法(比如colors.slate.800/50),这是因为这种写法是Tailwind类名的语法糖,并非配置层面的合法调用方式。你可以用以下两种方法实现需求:
方案一:利用CSS变量结合rgba()
Tailwind v3会将所有内置颜色注册为CSS变量,格式为--tw-color-{颜色名}-{色阶},变量值是颜色的RGB通道数值(例如slate.800对应的变量值是30 41 59)。你可以通过rgba()语法,基于这些变量快速添加透明度:
修改你的代码如下:
typography (theme) { return { DEFAULT: { css: { 'code::before': { content: 'none', }, 'code::after': { content: 'none' }, code: { color: theme('colors.slate.700'), fontWeight: "400", backgroundColor: 'rgba(var(--tw-color-stone-100), 0.3)', // 30%透明度的stone.100 borderRadius: theme('borderRadius.DEFAULT'), borderWidth: '1px', paddingLeft: theme('spacing[1.5]'), paddingRight: theme('spacing[1.5]'), paddingTop: theme('spacing[0.5]'), paddingBottom: theme('spacing[0.5]'), }, } }, invert: { css: { code: { color: theme('colors.slate.100'), backgroundColor: 'rgba(var(--tw-color-slate-800), 0.5)', // 50%透明度的slate.800 borderColor: theme('colors.slate.600'), } } } } },
方案二:手动使用颜色的RGB值
如果你知道目标内置颜色的RGB数值,也可以直接写死在rgba()中,比如slate.800的RGB是30, 41, 59,那么50%透明度的写法就是rgba(30, 41, 59, 0.5)。这种方法不需要依赖CSS变量,但灵活性稍差,当Tailwind版本更新颜色值时需要手动同步。
内容的提问来源于stack exchange,提问作者Blue Waters
相关产品推荐
相关产品推荐

