【问题标题】:Tailwind: How to make @apply work for custom CSS class?Tailwind:如何让 @apply 为自定义 CSS 类工作?
【发布时间】:2022-01-14 11:51:45
【问题描述】:

假设你有一个基本的项目设置:

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

并且您想添加一个基本实用程序,该实用程序使用不属于 tailwinds 默认库的 CSS:

@layer utilities {
  .will-change-transform {
    will-change: transform;
  }
}

@layer utilities {
  .ease {
    transition: ease;
  }
}

并且您希望能够将其@apply 发送到自定义类而不会收到错误:

.my-component {
  @apply block hover:scale-110 w-full ease will-change-transform
}

你会怎么做?

【问题讨论】:

    标签: css tailwind-css


    【解决方案1】:

    好像你有点搞砸了setupconfig :-) 链接到source

    globals.css

    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
    @layer components {
      .btn {
        @apply bg-red-600 py-3 px-6 rounded-md ring-gray-200 text-sm text-white hover:ring-1 focus:outline-none active:ring-gray-300 hover:shadow-md hover:bg-white hover:text-red-600 hover:ring-red-600;
      }
    
      .link {
        @apply hover:underline cursor-pointer;
      }
    }
    

    <button className="btn link">Click me</button>
    

    这里有上面代码的工作示例,带有来自docs 的特殊(添加一些自定义 CSS)挂钩:

    <!doctype html>
    <html>
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="https://cdn.tailwindcss.com"></script>
      <script>
        /* ... */
      </script>
      <style type="text/tailwindcss">@layer components {
      .btn {
        @apply bg-red-600 py-3 px-6 rounded-md ring-gray-200 text-sm text-white hover:ring-1 focus:outline-none active:ring-gray-300 hover:shadow-md hover:bg-white hover:text-red-600 hover:ring-red-600;
      }
    
      .link {
        @apply hover:underline cursor-pointer;
      }
    }</style>
    </head>
    
    <body>
      <div class="flex items-center justify-center h-screen flex-col">
        <h1 class="text-3xl">Hello Css Custom Class</h1>
        <button class="btn link mt-10">Click me</button>
      </div>
    </body>
    
    </html>

    【讨论】:

    • 嗨,这不是我要问的。您使用其他顺风类构建了这两个类。在这里,我说的是制作不是用@apply 构建的类,只是普通的css 属性和值,以及使那些普通的css 类@apply能够用于其他类。
    猜你喜欢
    • 2021-12-06
    • 2022-01-25
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 2021-07-19
    • 2020-04-12
    相关资源
    最近更新 更多