我定义了一个自定义 Tailwind 类,但似乎无法在我的 CSS 中使用它
@apply
。
在 Tailwind CSS 中,您可以在
tailwind.config.js
中添加自定义类,如下所示:
extend: {
boxShadow:{
"specific":'rgba(0, 0, 0, 0.16) 0px 3px 6px, rgba(0, 0, 0, 0.23) 0px 3px 6px'
}
}
我可以将此类添加到元素并看到阴影,但是当我尝试在
@apply
中使用它时,我收到此错误:
类不存在。如果shadow-specific
是自定义类,请确保它是在shadow-specific
指令中定义的。@layer
这是我如何使用该类
@apply
:
.product .title {
@apply py-2 font-extrabold text-lg md:text-base shadow-specific;
}
我还尝试使用
index.css
指令在 @layer
中定义类:
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
.shadow-specific {
box-shadow: rgba(0, 0, 0, 0.16) 0px 3px 6px, rgba(0, 0, 0, 0.23) 0px 3px 6px;
}
}
仍然没有运气。
使用 Astro 遇到了这个问题。事实证明这种行为是预期的。
如果您尝试在这些每个组件块之一中 @apply 在全局 CSS 中定义的自定义类,您将收到有关该类不存在的错误。
此问题的解决方案是使用插件系统定义您想要在组件中 @apply 的任何自定义样式。
const plugin = require('tailwindcss/plugin')
module.exports = {
// ...
plugins: [
plugin(function ({ addComponents, theme }) {
addComponents({
'.shadow-specific': {
boxShadow: theme('boxShadow.xl'),
}
})
})
]
}
参考:https://tailwindcss.com/docs/functions-and-directives#using-apply-with-per-component-css
类不应该在@apply中。
正确做法:
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components{
.shadow-specific{
box-shadow: rgba(0, 0, 0, 0.16) 0px 3px 6px, rgba(0, 0, 0, 0.23) 0px 3px 6px;
}
}
然后以您的组件为例:
<div className="shadow-specific">