Tailwind CSS Academy · 강의

재사용 가능한 컴포넌트 클래스 만들기

@apply를 사용해 전역 CSS 파일에 .btn, .card, .badge 클래스를 만들고 HTML 템플릿의 중복을 줄입니다.

레슨 2/413개 단계

재사용 가능한 컴포넌트 클래스 만들기은(는) CoddyKit의 무료 Tailwind CSS Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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.

무료로 시작

AI 튜터와 함께 HTML을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
30
레슨
120

자주 묻는 질문

“재사용 가능한 컴포넌트 클래스 만들기” 강의는 무료인가요?

네 — “재사용 가능한 컴포넌트 클래스 만들기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Tailwind CSS Academy 강의 전체를 잠금 해제할 수 있습니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“재사용 가능한 컴포넌트 클래스 만들기”에서 뭘 배우나요?

@apply를 사용해 전역 CSS 파일에 .btn, .card, .badge 클래스를 만들고 HTML 템플릿의 중복을 줄입니다. 브라우저에서 직접 실행하는 실습 코드로 Tailwind CSS Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Tailwind CSS Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Tailwind CSS Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“재사용 가능한 컴포넌트 클래스 만들기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Tailwind CSS Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Tailwind CSS Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. @apply의 기능과 사용 시점
  2. 재사용 가능한 컴포넌트 클래스 만들기
  3. 레이어를 사용한 사용자 지정 CSS 구성
  4. @apply의 주의점과 대안
← Tailwind CSS Academy(으)로 돌아가기