@apply의 기능과 사용 시점
@apply가 유틸리티 클래스를 CSS 규칙 안에 인라인으로 삽입하는 방식을 이해하고, 클래스를 추출하는 것이 적절한 상황을 파악합니다.
@apply의 기능과 사용 시점은(는) CoddyKit의 무료 Tailwind CSS Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Tailwind CSS Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
The Problem @apply Solves
Tailwind's utility-first approach places all styles directly on HTML elements. For simple pages, this is fine. But when the same combination of 15 utility classes appears on 50 button elements, updating a single design detail requires changing 50 places. The @apply directive solves this by letting you extract frequently repeated utility combinations into a single custom CSS class — without giving up Tailwind's utility system.
How @apply Works
@apply is a PostCSS directive that Tailwind processes during compilation. When Tailwind encounters @apply bg-blue-600 text-white font-semibold inside a CSS rule, it inlines the CSS declarations that those utilities would generate. The resulting CSS rule contains the actual property values, not Tailwind class names. The final browser output has no knowledge of Tailwind or @apply.
/* Your CSS with @apply */
@layer components {
.btn {
@apply px-4 py-2 rounded-lg font-semibold text-sm;
}
.btn-primary {
@apply btn bg-blue-600 text-white hover:bg-blue-700;
}
}
/* Compiled output (what the browser sees) */
.btn {
padding: 0.5rem 1rem;
border-radius: 0.5rem;
font-weight: 600;
font-size: 0.875rem;
}
.btn-primary {
/* btn styles + primary colors */
}Writing @apply in a CSS File
Use @apply inside CSS files that are processed by Tailwind. Always wrap extracted component classes in an @layer components block so Tailwind inserts them in the correct position in the generated stylesheet — after base styles but before utility classes. This ensures utility classes applied directly in HTML can still override your component class styles.
/* styles/components.css or in your main CSS file */
@layer components {
.btn {
@apply inline-flex items-center justify-center
px-4 py-2 rounded-lg text-sm font-semibold
transition-colors duration-150
focus:outline-none focus:ring-2 focus:ring-offset-2;
}
.btn-primary {
@apply btn bg-blue-600 text-white
hover:bg-blue-700
focus:ring-blue-500;
}
.btn-secondary {
@apply btn bg-gray-200 text-gray-800
hover:bg-gray-300
focus:ring-gray-500;
}
}When to Use @apply
The right situations for @apply are narrow and specific. Use it when: the same utility combination appears verbatim in 5 or more places; the component is rendered in a context where you cannot control the HTML (like markdown-rendered content or a third-party component); or when framework limitations make class-based conditional logic impractical. If you can use JSX components, Vue components, or HTML partials instead, those are almost always a better choice.
Common @apply Use Cases
Practical @apply use cases include: base button styles shared across many button instances, form input reset styles applied uniformly, typography styles for markdown-rendered blog content, and utility classes embedded in third-party component HTML you cannot modify. In all these cases, the common thread is that you cannot put the utility classes directly on the HTML element that needs them.
@layer components {
/* Used in markdown-rendered content where you can't add classes to elements */
.content h1 { @apply text-3xl font-bold mb-4 text-gray-900; }
.content h2 { @apply text-2xl font-semibold mb-3 text-gray-800; }
.content p { @apply text-gray-600 leading-relaxed mb-4; }
.content a { @apply text-blue-600 underline hover:text-blue-800; }
.content ul { @apply list-disc list-inside mb-4 space-y-1; }
/* Shared input base */
.form-field {
@apply w-full rounded-lg border border-gray-300 px-4 py-2
focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm;
}
}The @layer Directive
Tailwind has three layers: base, components, and utilities. Use @layer base for element resets and global defaults. Use @layer components for extracted component classes built with @apply. Use @layer utilities for custom single-purpose utility classes. The layer order ensures utility classes always override component classes, which override base styles — maintaining the expected specificity hierarchy.
@layer base {
/* Global resets and element defaults */
body { @apply font-sans text-gray-900 antialiased; }
a { @apply text-blue-600 hover:underline; }
}
@layer components {
/* Extracted multi-utility patterns */
.card { @apply bg-white rounded-xl shadow p-6; }
}
@layer utilities {
/* Custom single-purpose utilities */
.text-balance { text-wrap: balance; }
}Applying Modifiers With @apply
You can use state and responsive modifiers inside @apply just like in HTML. Write hover:bg-blue-700, focus:ring-2, or md:flex directly in your @apply statement and Tailwind generates the correct selector-based CSS. This is one of the reasons @apply is more powerful than manually writing CSS — you get the full variant system without any extra effort.
@layer components {
.badge {
@apply
inline-flex items-center px-2.5 py-0.5 rounded-full
text-xs font-medium
bg-gray-100 text-gray-700
/* Hover state */
hover:bg-gray-200
/* Dark mode */
dark:bg-gray-700 dark:text-gray-300
dark:hover:bg-gray-600
/* Transition */
transition-colors duration-150;
}
}Chaining @apply Classes
You can reference other component classes created with @apply inside another @apply. For example, define a .btn base class and then reference it in .btn-primary to inherit all the base button styles. This creates a simple inheritance chain. Be cautious about deep nesting — it creates implicit dependencies that can be hard to trace when debugging.
@layer components {
/* Base class */
.btn {
@apply inline-flex items-center px-4 py-2 rounded-lg
text-sm font-medium transition-colors duration-150
focus:outline-none focus:ring-2 focus:ring-offset-2;
}
/* Variants inherit from .btn */
.btn-primary { @apply btn bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500; }
.btn-danger { @apply btn bg-red-600 text-white hover:bg-red-700 focus:ring-red-500; }
.btn-ghost { @apply btn text-gray-700 hover:bg-gray-100 focus:ring-gray-400; }
}@apply in SFC Styles
In Vue Single File Components (SFCs) and some React setups with CSS Modules, you can use @apply inside the component's <style> block. This keeps component styles co-located with the template while still using Tailwind utilities as building blocks. Configure your bundler to process these style blocks through PostCSS with the Tailwind plugin to enable @apply.
<!-- Vue SFC with @apply in <style> -->
<template>
<button class="btn">Click Me</button>
</template>
<style scoped>
.btn {
@apply bg-blue-600 text-white px-4 py-2 rounded-lg
font-medium hover:bg-blue-700
transition-colors duration-150;
}
</style>The Right Question: Is @apply Needed?
Before reaching for @apply, always ask: can I extract this into a component instead? In React, this means a Button component that accepts a variant prop. In HTML, it means a partial or template include. Component extraction is usually better than @apply because it is explicit, searchable, and works with all frameworks. Use @apply only when component extraction is not possible or practical.
/* Instead of @apply in a CSS file... */
.btn-primary { @apply bg-blue-600 text-white px-4 py-2 rounded-lg; }
/* Prefer a JSX component */
function Button({ children, variant = 'primary' }) {
const styles = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-200 text-gray-800 hover:bg-gray-300',
};
return (
<button className={'px-4 py-2 rounded-lg font-medium ' + styles[variant]}>
{children}
</button>
);
}Verifying @apply Output
After writing an @apply rule, verify it compiles correctly by building your CSS and inspecting the output. Search the compiled CSS file for the class name you created. You should see the full CSS declarations inlined — not @apply syntax, which is stripped during compilation. If the class is missing or shows unexpected properties, check the @layer placement and ensure all referenced utilities are valid Tailwind classes.
# Build and search for your custom class
npx tailwindcss -i ./src/input.css -o ./dist/output.css
grep '.btn-primary' ./dist/output.css
# Or watch mode for real-time feedback
npx tailwindcss -i ./src/input.css -o ./dist/output.css --watchQuick Check
Test your understanding of the @apply directive in Tailwind CSS.
Lesson Recap
In this lesson you learned: @apply inlines utility class CSS into a custom class name and is ideal for content you cannot add classes to directly, always place @apply-based classes inside @layer components to maintain proper specificity, and component extraction (JSX, Vue SFC, HTML partials) is usually preferable to @apply when possible. Next up we build reusable component classes with @apply.
AI 튜터와 함께 HTML을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 30
- 레슨
- 120
자주 묻는 질문
“@apply의 기능과 사용 시점” 강의는 무료인가요?
네 — “@apply의 기능과 사용 시점” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Tailwind CSS Academy 강의 전체를 잠금 해제할 수 있습니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“@apply의 기능과 사용 시점”에서 뭘 배우나요?
@apply가 유틸리티 클래스를 CSS 규칙 안에 인라인으로 삽입하는 방식을 이해하고, 클래스를 추출하는 것이 적절한 상황을 파악합니다. 브라우저에서 직접 실행하는 실습 코드로 Tailwind CSS Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Tailwind CSS Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Tailwind CSS Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“@apply의 기능과 사용 시점” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Tailwind CSS Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Tailwind CSS Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- @apply의 기능과 사용 시점
- 재사용 가능한 컴포넌트 클래스 만들기
- 레이어를 사용한 사용자 지정 CSS 구성
- @apply의 주의점과 대안