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

使用TailwindCSS CDN时@apply指令失效,如何解决?

问题原因

CDN引入的Tailwind CSS默认不支持解析外部CSS文件中的@apply、@layer等指令。因为CDN版本是预编译好的成品样式,它只会处理页面内的特定代码,没法读取并编译你本地的styles.css文件里的Tailwind语法。

解决方案

如果不想配置tailwind.config.js,继续用CDN方式,把自定义的组件样式放到HTML页面内的<style>标签里,并且确保这个标签在Tailwind的CDN脚本之后:

<!DOCTYPE html>
<html lang="en">
<head>    
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    @layer components {
      .btnhello {
        @apply mx-12 my-12 rounded-xl bg-yellow-400 hover:bg-yellow-500 active:bg-yellow-200 p-10;
      }
    }
  </style>
</head>
<body>
  <button type="button" class="mx-12 my-12 rounded-xl bg-blue-400 hover:bg-yellow-500 active:bg-yellow-200 p-10">Click me</button>
  <button type="button" class="btnhello">Click me</button>
</body>
</html>

Tailwind的CDN版本会自动扫描页面内带有@layer的<style>标签,处理其中的@apply指令,这样自定义的.btnhello类就能正常生效了。

如果坚持要用外部CSS文件,那就必须本地安装Tailwind CLI或PostCSS工具,配合tailwind.config.js来编译你的样式文件,这就打破了你“无需配置”的初衷,所以优先推荐上面的页面内样式写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 21:25:14