0Pricing
Tailwind CSS Academy · 课时

创建可复用的组件 class

使用 @apply 在全局 CSS 文件中构建 .btn、.card 和 .badge class,减少 HTML 模板中的重复内容。

创建可复用的组件 class 是 CoddyKit 上的免费 Tailwind CSS Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Tailwind CSS Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Tailwind CSS Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Component Classes vs Utility Classes

Tailwind encourages utility-first — applying single-purpose classes directly to HTML. But for complex components like buttons, cards, and badges that appear throughout a project, extracting them into component classes with @apply reduces repetition and creates a consistent, named vocabulary for your team. The goal is not to recreate traditional CSS but to create a small set of high-value abstractions where duplication is genuinely costly.

Creating a Button Component Class

A button is one of the best candidates for a component class because every interactive UI has many buttons with the same core styles. Define a base .btn class for shared structure, then create modifier classes like .btn-primary, .btn-secondary, and .btn-outline for variants. Users apply both classes to get the full button style without knowing the underlying utilities.

@layer components {
  .btn {
    @apply inline-flex items-center justify-center gap-2
           px-4 py-2 rounded-lg text-sm font-semibold
           transition-all duration-150
           focus:outline-none focus:ring-2 focus:ring-offset-2
           disabled:opacity-50 disabled:cursor-not-allowed;
  }

  .btn-primary {
    @apply btn bg-blue-600 text-white
           hover:bg-blue-700 active:bg-blue-800
           focus:ring-blue-500;
  }

  .btn-outline {
    @apply btn border border-gray-300 text-gray-700 bg-white
           hover:bg-gray-50 active:bg-gray-100
           focus:ring-gray-400;
  }
}

Using Button Component Classes in HTML

With component classes defined, HTML becomes concise and readable. Apply btn btn-primary for a primary button or btn btn-outline for a secondary option. Individual utility classes can still be added to override specific properties — for example, w-full to make a button stretch full width — because utilities always win over component classes in the Tailwind layer hierarchy.

<!-- Clean, readable HTML using component classes -->
<button class="btn btn-primary">Save Changes</button>
<button class="btn btn-outline">Cancel</button>

<!-- Utility override still works -->
<button class="btn btn-primary w-full">Full Width Button</button>

<!-- Disabled state from btn class -->
<button class="btn btn-primary" disabled>Loading...</button>

Creating a Card Component Class

Cards are container components that wrap content sections. A .card base class handles the visual container, while modifier classes like .card-compact or .card-bordered add variations. This pattern keeps the HTML clean while allowing flexible configuration — a developer adds card for the default look and optionally adds a modifier for a variant.

@layer components {
  .card {
    @apply bg-white rounded-xl shadow-sm border border-gray-200
           overflow-hidden;
  }

  .card-body {
    @apply p-6;
  }

  .card-header {
    @apply px-6 py-4 border-b border-gray-100 font-semibold text-gray-900;
  }

  .card-footer {
    @apply px-6 py-4 border-t border-gray-100 bg-gray-50 flex justify-end gap-3;
  }

  /* Dark mode variant */
  .dark .card {
    @apply bg-gray-800 border-gray-700;
  }
}

Badge Component Classes

Badges are small pill-shaped labels used for status indicators, counts, and category tags. They are an excellent candidate for component classes because they appear frequently and always have the same pill shape. Define a base .badge class and color modifier classes. Keep them small and focused — badges should not have complex internal structure.

@layer components {
  .badge {
    @apply inline-flex items-center px-2.5 py-0.5 rounded-full
           text-xs font-medium;
  }

  .badge-blue   { @apply badge bg-blue-100 text-blue-700; }
  .badge-green  { @apply badge bg-green-100 text-green-700; }
  .badge-yellow { @apply badge bg-yellow-100 text-yellow-700; }
  .badge-red    { @apply badge bg-red-100 text-red-700; }
  .badge-gray   { @apply badge bg-gray-100 text-gray-600; }
}

<!-- Usage -->
<span class="badge-green">Active</span>
<span class="badge-red">Overdue</span>

Form Input Component Classes

Form inputs have many shared styles — border, padding, border-radius, focus ring — that repeat across every text field, textarea, and select in a project. Extract these into a .form-input class and modifier classes for states. This is especially useful when combined with the @tailwindcss/forms plugin which normalizes browser default styles first.

@layer components {
  .form-field {
    @apply w-full rounded-lg border border-gray-300 bg-white
           px-4 py-2.5 text-sm text-gray-900
           placeholder:text-gray-400
           focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent
           dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100
           dark:placeholder:text-gray-500;
  }

  .form-field-error {
    @apply form-field border-red-500 focus:ring-red-500;
  }

  .form-label {
    @apply block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1;
  }
}

Alert and Toast Component Classes

Alerts communicate important feedback to users and appear in multiple semantic variants: info, success, warning, and error. Each shares the same structure but uses different colors. Define a base .alert class for layout and a set of modifier classes for each semantic type. The base handles padding, border-radius, and icon alignment, while modifiers handle the color theme.

@layer components {
  .alert {
    @apply flex items-start gap-3 p-4 rounded-lg text-sm;
  }

  .alert-info    { @apply alert bg-blue-50 text-blue-800 border border-blue-200; }
  .alert-success { @apply alert bg-green-50 text-green-800 border border-green-200; }
  .alert-warning { @apply alert bg-yellow-50 text-yellow-800 border border-yellow-200; }
  .alert-error   { @apply alert bg-red-50 text-red-800 border border-red-200; }
}

<!-- Usage -->
<div class="alert-success">
  <span>Your profile was saved successfully.</span>
</div>

Navigation Link Classes

Navigation links are another prime candidate for component classes because they always have the same base look with active state variations. Define a .nav-link class for the default state and an .nav-link-active class for the highlighted current page link. If you are using a JavaScript framework, you would typically apply the active class programmatically based on the current route.

@layer components {
  .nav-link {
    @apply flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium
           text-gray-600 hover:bg-gray-100 hover:text-gray-900
           transition-colors duration-150;
  }

  .nav-link-active {
    @apply nav-link bg-blue-50 text-blue-700 hover:bg-blue-100;
  }
}

<nav>
  <a href="/" class="nav-link-active">Dashboard</a>
  <a href="/settings" class="nav-link">Settings</a>
</nav>

Organizing Component Classes in Files

As your component class count grows, keep them organized in dedicated CSS files grouped by category. Import them all into your main CSS entry file using @import or by importing multiple files through PostCSS. A typical structure has separate files for buttons, forms, cards, badges, navigation, and typography — all within the @layer components scope.

/* src/styles/main.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

/* Component class files */
@import './components/buttons.css';
@import './components/cards.css';
@import './components/badges.css';
@import './components/forms.css';
@import './components/navigation.css';

/* Custom utilities */
@import './utilities/text-balance.css';

Component Classes With Size Modifiers

Many components come in different sizes — small, medium, and large. Define size modifier classes that override the padding and font size from the base class. Because size modifiers are applied after the base class in the CSS source (within the same layer), they correctly override the base values without needing higher specificity or !important.

@layer components {
  /* Base button */
  .btn { @apply inline-flex items-center px-4 py-2 rounded-lg text-sm font-medium; }

  /* Size modifiers */
  .btn-xs  { @apply px-2.5 py-1.5 text-xs rounded; }
  .btn-sm  { @apply px-3 py-1.5 text-sm rounded-md; }
  .btn-lg  { @apply px-5 py-2.5 text-base rounded-lg; }
  .btn-xl  { @apply px-6 py-3 text-lg rounded-xl; }
}

<!-- Usage -->
<button class="btn btn-primary btn-sm">Small Primary</button>
<button class="btn btn-primary">Default Primary</button>
<button class="btn btn-primary btn-lg">Large Primary</button>

Testing Component Classes

Build a simple visual test page that shows every component class variant side by side. This serves as a living style guide and catches regressions when you modify the component classes. Include every size, color, and state variant. Share this page with designers to verify the component classes match the intended design system specification before using them in production.

<!-- Component test page snippet -->
<div class="p-8 space-y-8">
  <div>
    <h3 class="text-xs font-mono text-gray-400 mb-3">Buttons</h3>
    <div class="flex flex-wrap gap-3">
      <button class="btn btn-primary">Primary</button>
      <button class="btn btn-outline">Outline</button>
      <button class="btn btn-primary" disabled>Disabled</button>
    </div>
  </div>
  <div>
    <h3 class="text-xs font-mono text-gray-400 mb-3">Badges</h3>
    <div class="flex flex-wrap gap-2">
      <span class="badge-blue">Blue</span>
      <span class="badge-green">Green</span>
      <span class="badge-red">Red</span>
    </div>
  </div>
</div>

Quick Check

Test your understanding of creating reusable component classes with Tailwind's @apply directive.

Lesson Recap

In this lesson you learned: define base + modifier component classes using @apply inside @layer components for buttons, cards, and badges, size modifiers let a single base class support multiple size variants, and component classes should be organized into separate files by category as the project grows. Next up we explore Tailwind's @layer system for organizing custom CSS.

常见问题解答

「创建可复用的组件 class」课时是免费的吗?

是的 — 「创建可复用的组件 class」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Tailwind CSS Academy 课程的其余内容,请升级到 CoddyKit PRO。 Tailwind CSS Academy 课程共包含 4 节课。

「创建可复用的组件 class」这节课中我会学到什么?

使用 @apply 在全局 CSS 文件中构建 .btn、.card 和 .badge class,减少 HTML 模板中的重复内容。 你通过在浏览器中直接运行的动手代码来练习 Tailwind CSS Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Tailwind CSS Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Tailwind CSS Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「创建可复用的组件 class」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Tailwind CSS Academy 课中编写并运行代码吗?

能。每节 Tailwind CSS Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. @apply 的作用与使用时机
  2. 创建可复用的组件 class
  3. 使用图层组织自定义 CSS
  4. @apply 的常见问题与替代方案
← 返回 Tailwind CSS Academy