ما الذي يفعله @apply ومتى يُستخدم
افهم كيف يضمّن @apply فئات الأدوات داخل قاعدة CSS، وحدّد الحالات التي يكون فيها استخراج فئة منفصلة منطقيًا.
ما الذي يفعله @apply ومتى يُستخدم درس مجاني في Tailwind CSS Academy على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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.
الأسئلة الشائعة
هل درس «ما الذي يفعله @apply ومتى يُستخدم» مجاني؟
نعم — نص درس «ما الذي يفعله @apply ومتى يُستخدم» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Tailwind CSS Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Tailwind CSS Academy 4 دروس في المجموع.
ماذا ستتعلم في «ما الذي يفعله @apply ومتى يُستخدم»؟
افهم كيف يضمّن @apply فئات الأدوات داخل قاعدة CSS، وحدّد الحالات التي يكون فيها استخراج فئة منفصلة منطقيًا. تتمرن على Tailwind CSS Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Tailwind CSS Academy؟
لا تُشترط خبرة سابقة. Tailwind CSS Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.
كم من الوقت يستغرق درس «ما الذي يفعله @apply ومتى يُستخدم»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Tailwind CSS Academy هذا؟
نعم. كل درس في Tailwind CSS Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- ما الذي يفعله @apply ومتى يُستخدم
- إنشاء فئات مكوّنات قابلة لإعادة الاستخدام
- تنظيم CSS المخصّص باستخدام الطبقات
- مشكلات @apply والبدائل