Tailwind CSS Academy · 강의

@apply의 주의점과 대안

@apply의 일반적인 잘못된 사용을 파악하고 우선순위에 미치는 영향을 이해하며 JSX 컴포넌트와 같은 컴포넌트 추출 대안을 평가합니다.

레슨 4/413개 단계

@apply의 주의점과 대안은(는) CoddyKit의 무료 Tailwind CSS Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Tailwind CSS Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

When @apply Causes Problems

While @apply seems like a convenient way to organize styles, overusing it creates a set of well-documented problems. These include difficulty in understanding which utilities are active, loss of single-source-of-truth for component styles, and specificity surprises. Understanding these pitfalls helps you decide when @apply is genuinely the right tool versus when a better alternative exists.

Pitfall 1: Recreating Traditional CSS

The most common misuse of @apply is using it to recreate conventional CSS classes — making every element have a single semantic class like .header-title and then filling it with utilities. This is exactly the pattern Tailwind was designed to move away from. You end up with the downsides of both approaches: verbose CSS files AND HTML that requires knowing which CSS classes exist. The result is harder to maintain than either approach alone.

/* ANTI-PATTERN: Recreating traditional CSS with @apply */
.page-header { @apply bg-white border-b px-6 py-4; }
.page-title  { @apply text-2xl font-bold text-gray-900; }
.page-meta   { @apply text-sm text-gray-500 mt-1; }
.page-action { @apply ml-auto; }

/* BETTER: Just write the utilities directly in HTML -->
<header class="bg-white border-b px-6 py-4">
  <h1 class="text-2xl font-bold text-gray-900">Title</h1>
  <p class="text-sm text-gray-500 mt-1">Meta</p>
</header>

Pitfall 2: Losing Variant Discoverability

When you hide utility classes inside @apply rules in a CSS file, they become invisible to the JIT scanner unless the CSS file is listed in your content array. More critically, future developers reading your HTML cannot see all the styles at a glance — they must open the CSS file, find the class, and mentally expand the @apply. This reduces the self-documenting nature of Tailwind's utility-first approach.

/* CSS: @apply hides what the component looks like */
.hero-button {
  @apply px-8 py-3 bg-indigo-600 text-white rounded-full font-semibold
         hover:bg-indigo-500 shadow-lg hover:shadow-indigo-500/50
         transition-all duration-200;
}

<!-- HTML: developer sees only the class name, not the styles -->
<button class="hero-button">Get Started</button>

<!-- Better: developer sees everything at a glance -->
<button class="px-8 py-3 bg-indigo-600 text-white rounded-full font-semibold hover:bg-indigo-500 shadow-lg transition-all duration-200">
  Get Started
</button>

Pitfall 3: Specificity Surprises

When you use @apply without placing the result in @layer components, the compiled CSS block sits at the location in your stylesheet where you wrote it. This can cause unexpected specificity issues where your component class wins over inline utilities because it appears later in the file. Always use @layer components to ensure the layer cascade handles specificity predictably.

/* BAD: No @layer wrapper — could override utilities unexpectedly */
.btn-primary {
  @apply bg-blue-600 text-white;
}

/* Later in the same file: */
/* p-4 might not override .btn-primary if placed before it */

/* GOOD: Use @layer components */
@layer components {
  .btn-primary {
    @apply bg-blue-600 text-white;
  }
  /* Now utilities always override correctly */
}

Pitfall 4: Cannot Use @apply with Arbitrary Values

Tailwind's arbitrary value syntax (bracket notation like w-[347px] or bg-[#1a2b3c]) does NOT work inside @apply. This is a fundamental limitation — arbitrary values are resolved by the JIT scanner finding them in source files, but @apply operates at a different stage. If your component requires one-off values, you must use plain CSS properties inside the rule rather than arbitrary-value utilities.

/* ERROR: Arbitrary values in @apply don't work */
.hero {
  @apply w-[347px] bg-[#1a2b3c];  /* Will not compile! */
}

/* CORRECT: Use plain CSS for arbitrary values */
.hero {
  @apply rounded-xl shadow-lg;  /* Regular utilities work fine */
  width: 347px;               /* Plain CSS for the arbitrary value */
  background-color: #1a2b3c;  /* Plain CSS for custom color */
}

The Real Alternative: JSX Components

In React and other component frameworks, the best alternative to @apply is a component abstraction. A Button component accepts a variant prop and renders the correct utility classes internally. The styles are encapsulated, the API is typed, and changes propagate everywhere the component is used. This is the pattern recommended by the Tailwind team for component-heavy codebases.

// React component replaces @apply .btn-primary
const variantStyles = {
  primary: 'bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500',
  outline: 'border border-gray-300 text-gray-700 hover:bg-gray-50',
  ghost:   'text-gray-600 hover:bg-gray-100 hover:text-gray-900',
};

export function Button({ variant = 'primary', children, ...props }) {
  return (
    <button
      className={'inline-flex items-center px-4 py-2 rounded-lg text-sm font-medium transition-colors ' + variantStyles[variant]}
      {...props}
    >
      {children}
    </button>
  );
}

The clsx Library for Conditional Classes

The clsx library (or its alternative classnames) makes conditional class composition clean in JavaScript. Instead of string concatenation or template literals, pass an object or array to clsx and it handles the conditional joining. This is the canonical way to manage variant classes in React components without @apply.

import clsx from 'clsx';

function Button({ variant, size, fullWidth, children }) {
  return (
    <button className={clsx(
      'inline-flex items-center justify-center rounded-lg font-medium transition-colors',
      {
        'px-4 py-2 text-sm': size === 'md' || !size,
        'px-3 py-1.5 text-xs': size === 'sm',
        'px-6 py-3 text-base': size === 'lg',
      },
      {
        'bg-blue-600 text-white hover:bg-blue-700': variant === 'primary',
        'border border-gray-300 text-gray-700 hover:bg-gray-50': variant === 'outline',
      },
      fullWidth && 'w-full',
    )}>
      {children}
    </button>
  );
}

HTML Template Partials as an Alternative

In non-framework HTML projects (like server-rendered apps using Django, Laravel, or Go templates), the equivalent of a component is a template partial or include. Extract the repeated HTML snippet with its utilities into a partial and include it wherever needed. This gives the same duplication benefit as @apply but keeps styles in the HTML where they belong.

<!-- Jinja2 / Django example -->
<!-- templates/components/button.html -->
<button class="inline-flex items-center px-4 py-2 rounded-lg font-medium text-sm bg-blue-600 text-white hover:bg-blue-700 transition-colors" type="{{ type|default:'button' }}">
  {{ label }}
</button>

<!-- Used via include -->
{% include 'components/button.html' with label='Save' type='submit' %}

When @apply IS the Right Choice

After understanding the pitfalls, you can identify the genuine cases where @apply is the correct tool. These include: styling HTML you cannot control (rendered markdown, CMS output, third-party library HTML), normalizing browser form elements alongside the forms plugin, and adding Tailwind utilities to external SVG or canvas elements. In these cases, you cannot add a class to the element, so @apply is the only option.

@layer components {
  /* Styling markdown content rendered by a CMS */
  .prose-content h1 { @apply text-4xl font-bold text-gray-900 mb-6 mt-8; }
  .prose-content h2 { @apply text-3xl font-semibold text-gray-800 mb-4 mt-6; }
  .prose-content p  { @apply text-gray-600 leading-relaxed mb-4; }
  .prose-content a  { @apply text-blue-600 underline underline-offset-2 hover:text-blue-800; }
  .prose-content ul { @apply list-disc list-inside space-y-1 mb-4 text-gray-600; }
}

The Tailwind Team's Official Guidance

The Tailwind CSS team explicitly recommends against using @apply to organize styles just because it 'feels cleaner.' Their documentation states: "If you find yourself wanting to use @apply to DRY up your Tailwind CSS, you should probably be using a component." Component abstractions are more explicit, more searchable, and more maintainable at scale. @apply should be a last resort, not a first impulse.

Refactoring @apply to Components

If you have an existing project with heavy @apply usage, you can refactor toward components incrementally. Start with the most frequently used component class (usually buttons or cards), create a proper component, and replace usages one file at a time. Each replacement improves type safety, colocation of styles, and readability. The migration is low-risk because the visual output should be identical — you are only changing the mechanism, not the design.

/* BEFORE: @apply in CSS */
@layer components {
  .btn-primary { @apply bg-blue-600 text-white px-4 py-2 rounded-lg font-medium; }
}

<!-- BEFORE: HTML -->
<button class="btn-primary">Save</button>

/* AFTER: Component abstraction */
// Button.jsx
export function Button({ children }) {
  return <button className="bg-blue-600 text-white px-4 py-2 rounded-lg font-medium">{children}</button>;
}

// usage
<Button>Save</Button>

Quick Check

Test your understanding of @apply pitfalls and alternatives.

Lesson Recap

In this lesson you learned: @apply pitfalls include recreating traditional CSS, hiding styles from HTML readers, and not working with arbitrary values, better alternatives are JSX components with clsx for React or template partials for server-rendered apps, and @apply should be reserved for HTML you cannot control like CMS-rendered markdown. Next up we explore Tailwind's transition and animation utilities.

무료로 시작

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

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

코스
30
레슨
120

자주 묻는 질문

“@apply의 주의점과 대안” 강의는 무료인가요?

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

“@apply의 주의점과 대안”에서 뭘 배우나요?

@apply의 일반적인 잘못된 사용을 파악하고 우선순위에 미치는 영향을 이해하며 JSX 컴포넌트와 같은 컴포넌트 추출 대안을 평가합니다. 브라우저에서 직접 실행하는 실습 코드로 Tailwind CSS Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“@apply의 주의점과 대안” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

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