Software Engineer Encyclopedia
0%
Domain 07 · Frontend Engineering with Angular · Pillar

Tailwind CSS مع Angular: utility-first من غير فوضى

Tailwind CSS with Angular

Tailwind v4 مع Angular (esbuild/Vite-based builder): الإعداد عبر PostCSS، فكرة utility-first ولماذا تشتغل، الـ design tokens بـ @theme، responsive وstate variants، dark mode والـ RTL للعربي، تنظيم الـ classes في components، وإمتى تستخدمه وإمتى لأ — مع مقارنة بـ Angular Material والـ CSS العادي.

  • Intermediate
  • ~9 min read
  • 14 sections
  • 11 code examples
  • 1 diagrams
  • 5 questions
  • Priority L2 · Essential
  • Tailwind CSS v4.x · Angular 20/21 (application builder, esbuild + Vite dev server) — setup reviewed 2026-11-18 against angular.dev and tailwindcss.com

بعد الدرس ده هتقدر

  • تثبت Tailwind v4 في مشروع Angular عبر @tailwindcss/postcss و.postcssrc.json وتعرف ليه مفيش tailwind.config.js في الإعداد الافتراضي
  • تشرح utility-first وإزاي Tailwind بيولّد CSS للـ classes المستخدمة بس
  • تعرّف design tokens (ألوان، مسافات، خطوط) بـ @theme وتستخدمها
  • تبني layouts responsive بالـ breakpoint prefixes وstates (hover/focus/disabled/aria-*)
  • تطبق dark mode (media أو class) وتدعم RTL بالـ logical utilities (ms-/me-/ps-/pe-)
  • تنظم الـ classes: components صغيرة، class bindings، وإمتى @apply
  • تقرر بين Tailwind وAngular Material/CDK وCSS عادي حسب الفريق والمنتج

المتطلبات قبل ما تبدأ

01

Utility-first: ليه ناس كتير بتحبه وناس بتكرهه

What utility-first means
Basics

في الـ CSS التقليدي بتخترع اسم class (.order-card) وتكتب ستايله في ملف تاني. في Tailwind بتكتب الستايل مباشرة كـ classes صغيرة بيعمل كل واحد حاجة واحدة: p-4 rounded-lg shadow-sm bg-white. الفكرة إن «الأسماء» مش بتتخترع، والـ CSS ما بيكبرش مع كل feature، والتعديل بيحصل في مكان واحد (الـ template).

الحجةلصالح Tailwindضد
السرعةبتبني UI من غير ما تسيب الـ templateمنحنى تعلم للأسماء في الأول
حجم الـ CSSبيتولد للـ classes المستخدمة بس، فبيفضل صغيرالـ HTML بيبقى أطول
Consistencyالمسافات والألوان من scale ثابت (tokens)لو كل حد استخدم arbitrary values (p-[13px]) الفايدة بتضيع
الصيانةمفيش CSS «ميت» ولا خوف تمسح classtemplates مزدحمة لو ما اتقسمتش components
التصميممرن جدًا لتصميم مخصصمش design system جاهز: الـ components (dialog، datepicker) لسه عليك أو على مكتبة
02

الإعداد مع Angular (Tailwind v4)

Setup
Practical

الـ Angular application builder (esbuild + Vite dev server) بيدعم PostCSS، و Tailwind v4 بيشتغل كـ PostCSS plugin. الإعداد الرسمي (حسب angular.dev و tailwindcss.com وقت المراجعة):

Bash1) install
npm install tailwindcss @tailwindcss/postcss postcss
JSON2) .postcssrc.json in the project root
{
  "plugins": {
    "@tailwindcss/postcss": {}
  }
}
CSS3) src/styles.css
@import "tailwindcss";

خلاص. في v4 مفيش tailwind.config.js إجباري: الإعدادات بقت في الـ CSS نفسه (@theme)، والـ content detection تلقائي (بيلاقي الـ classes في ملفات المشروع). لو جاي من v3: autoprefixer مش لازم، والـ directives القديمة (@tailwind base...) اتبدلت بـ @import "tailwindcss" — في upgrade tool رسمي.

ملاحظات عملية

(1) لو بتستخدم SCSS كـ global stylesheet، Tailwind v4 مش مصمم يتعالج جوه Sass؛ خلي ملف styles.css عادي لـ Tailwind وملفات SCSS لحاجات تانية لو محتاج. (2) في monorepo (Nx) الـ scan التلقائي ممكن يلم classes من مشاريع تانية؛ حدد المصادر بـ @source لو الـ CSS كبر. (3) راجع صفحة الإعداد الرسمية لما تعمل upgrade لـ Angular أو Tailwind — الخطوات دي بالذات اتغيرت بين النسخ.

03

بيشتغل إزاي من جوه؟

How Tailwind generates CSS
Deep dive
*.html / *.tsclass="p-4 md:p-6dark:bg-gray-900"Scannerfinds candidate classstrings (static text)Generated CSSonly used utilities+ theme variablesRule: class names must appear as complete strings in source'bg-' + color ✗ (never generated) color === 'red' ? 'bg-red-600' : 'bg-green-600' ✓
Tailwind scans source files for class names and emits only the CSS for classes it finds

الـ scanner بيقرأ النص زي ما هو، ما بيشغلش الكود. يعني class اتركّب ديناميكيًا (`text-${size}`) مش هيتولد. الحل: map ثابت من القيم للـ classes الكاملة.

TypeScriptstatus badge: full class names in a map
const STATUS_CLASSES: Record<OrderStatus, string> = {
  pending:  'bg-amber-100 text-amber-800 ring-amber-600/20',
  shipped:  'bg-sky-100 text-sky-800 ring-sky-600/20',
  canceled: 'bg-rose-100 text-rose-800 ring-rose-600/20',
};

@Component({
  selector: 'app-status-badge',
  template: `<span class="inline-flex items-center rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset"
                   [class]="classes()">{{ label() }}</span>`,
})
export class StatusBadge {
  status = input.required<OrderStatus>();
  label = input('');
  classes = computed(() => STATUS_CLASSES[this.status()]);
}

ملاحظة: [class] binding بيدمج مع الـ static class attribute في Angular الحديث. لو حصل تعارض، استخدم [ngClass] أو حط الـ classes كلها في الـ computed.

04

Design tokens بـ @theme

Theme variables
Practical

بدل ما تحفظ ألوان Tailwind الافتراضية، عرّف tokens المنتج بتاعك، وكل الـ utilities بتتولد منهم تلقائيًا (bg-brand-600, font-display).

CSSsrc/styles.css
@import "tailwindcss";

@theme {
  --color-brand-50:  #fbf7f2;
  --color-brand-600: #906d4b;
  --color-brand-700: #594c3d;
  --color-ink-900:   #13191f;
  --font-display: "Cairo", "Inter", system-ui, sans-serif;
  --radius-card: 0.75rem;
  --breakpoint-3xl: 120rem;          /* adds a 3xl: variant */
}
/* utilities now exist: bg-brand-600, text-ink-900, font-display, rounded-card, 3xl:grid-cols-6 */

الـ tokens بتطلع CSS variables حقيقية، فتقدر تستخدمها في CSS عادي أو في components من مكتبات تانية: color: var(--color-brand-600). ده بيخلي Tailwind و Angular Material/CDK يتشاركوا نفس الـ palette.

05

Responsive والـ states

Responsive design and state variants
Practical
HTMLmobile-first card grid with accessible states
<section class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
  @for (doc of docs(); track doc.id) {
    <article class="rounded-card border border-gray-200 bg-white p-4 shadow-sm transition
                    hover:shadow-md focus-within:ring-2 focus-within:ring-brand-600
                    dark:border-gray-700 dark:bg-gray-900">
      <h3 class="font-display text-base font-semibold text-ink-900 dark:text-gray-100 line-clamp-2">{{ doc.title }}</h3>
      <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">{{ doc.updatedAt | date }}</p>
      <button class="mt-3 inline-flex items-center gap-2 rounded-md bg-brand-600 px-3 py-1.5 text-sm text-white
                     hover:bg-brand-700 focus-visible:outline-2 focus-visible:outline-offset-2
                     disabled:cursor-not-allowed disabled:opacity-50"
              [disabled]="doc.status !== 'ready'">Ask about this document</button>
    </article>
  }
</section>
  • Mobile-first: الـ class من غير prefix لكل الشاشات، و sm:/md:/lg: بتزود من عرض معين وطالع. ما تفكرش «desktop وبعدين أصلح الموبايل».
  • States: hover:، focus-visible: (للكيبورد بس)، disabled:، aria-expanded:، group-hover:، peer-invalid: (رسالة خطأ تظهر لما الـ input قبلها invalid).
  • Focus ظاهر دايمًا: ما تشيلش الـ outline من غير بديل — accessibility (HTML & CSS).
06

Dark mode والـ RTL للعربي

Dark mode and right-to-left
Practical

Dark mode: افتراضيًا dark: بيتبع prefers-color-scheme بتاع النظام. لو عايز زرار toggle في التطبيق، عرّف variant بيعتمد على class أو attribute:

CSSclass-based dark mode in v4
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
TypeScriptThemeService (signals): persist and apply
@Injectable({ providedIn: 'root' })
export class ThemeService {
  readonly mode = signal<'light' | 'dark'>(localStorage.getItem('theme') === 'dark' ? 'dark' : 'light');
  constructor() {
    effect(() => {
      document.documentElement.classList.toggle('dark', this.mode() === 'dark');
      localStorage.setItem('theme', this.mode());
    });
  }
  toggle() { this.mode.update(m => (m === 'dark' ? 'light' : 'dark')); }
}

RTL: مع <html dir="rtl" lang="ar"> استخدم الـ logical utilities بدل left/right: ms-4 (margin-inline-start) بدل ml-4، pe-2 بدل pr-2، text-start بدل text-left، start-0 بدل left-0. كده نفس الـ template بيشتغل عربي وإنجليزي. لما محتاج فرق حقيقي (أيقونة سهم): rtl:rotate-180.

07

تنظيم الـ classes: إمتى component وإمتى @apply

Keeping templates maintainable
Deep dive
الموقفالحل
نفس مجموعة الـ classes في 15 زرارAngular component (app-button) بـ inputs (variant، size) — مش copy-paste
Variants كتير لنفس الـ componentmap من variant لـ classes (زي الـ badge فوق)، أو مكتبة variants صغيرة
HTML مش انت متحكم فيه (markdown مترندر، rich text)@apply في CSS للـ selectors دي، أو typography plugin
Third-party component محتاج overrideCSS عادي بالـ tokens: var(--color-brand-600)
TypeScriptButtonComponent: the abstraction is the component, not a CSS class
type Variant = 'primary' | 'secondary' | 'danger';
const BASE = 'inline-flex items-center justify-center gap-2 rounded-md font-medium transition focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50 disabled:cursor-not-allowed';
const VARIANTS: Record<Variant, string> = {
  primary:   'bg-brand-600 text-white hover:bg-brand-700 focus-visible:outline-brand-600',
  secondary: 'bg-white text-ink-900 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-100',
  danger:    'bg-rose-600 text-white hover:bg-rose-700 focus-visible:outline-rose-600',
};
const SIZES = { sm: 'px-2.5 py-1.5 text-sm', md: 'px-3.5 py-2 text-sm', lg: 'px-4 py-2.5 text-base' } as const;

@Component({
  selector: 'button[appButton]',
  template: `<ng-content />`,
  host: { '[class]': 'classes()' },
})
export class AppButton {
  variant = input<Variant>('primary');
  size = input<keyof typeof SIZES>('md');
  classes = computed(() => `${BASE} ${VARIANTS[this.variant()]} ${SIZES[this.size()]}`);
}
// usage: <button appButton variant="danger" (click)="delete()">Delete</button>  (keeps native button semantics)

@apply ممكن يبان «أنضف»، لكن الإفراط فيه بيرجّعك لنفس مشاكل الـ CSS التقليدي (أسماء، ملفات، specificity). استخدمه للحالات اللي فوق بس. وفي Angular، لو استخدمت @apply جوه component styles محتاج @reference "../../styles.css"; في أول الملف عشان الـ utilities تبقى معروفة (v4).

08

إمتى Tailwind وإمتى لأ؟

Choosing a styling approach
Deep dive
الموقفالأنسب غالبًاليه
Admin/internal tool، فريق backend، وقت ضيقAngular Material (+ شوية Tailwind للـ layout)components جاهزة accessible (tables، dialogs، datepickers)
منتج SaaS بتصميم مخصص و brand قويTailwind + Angular CDK (behaviour من غير ستايل)تحكم كامل في الشكل، والـ CDK بيدّي accessibility للـ overlays والـ a11y
Design system قائم بـ CSS/SCSS كبيرCSS الموجودإعادة كتابة كل حاجة نادرًا بتستاهل
Landing pages ومحتوىTailwindسريع ومرن

القرار مش «أحسن framework»: هو مين هيكتب الـ UI، هل فيه designer و design tokens، ومحتاجين components معقدة جاهزة ولا لأ. والدمج شائع ومقبول: Material للـ components المعقدة و Tailwind للـ layout والـ spacing، بشرط إن الـ tokens (ألوان، خطوط) متوحدة.

09

Accessibility مع Tailwind: الحاجات اللي ما بتيجيش مجانًا

Accessibility you still own
Practical
  • Contrast: الألوان في الـ @theme لازم تعدّي WCAG (4.5:1 للنص العادي). اختبرها مرة في الـ design tokens بدل ما تختبر كل صفحة.
  • Screen-reader only text: sr-only للـ labels المخفية بصريًا (زرار أيقونة بس).
  • Motion: motion-reduce:transition-none للناس اللي مفعّلين reduced motion.
  • Focus: focus-visible:outline-2 focus-visible:outline-offset-2 على كل عنصر تفاعلي، ومتسق عبر الـ components (في الـ AppButton فوق).
  • Semantics: Tailwind ما بيعملش HTML صح: <button> مش <div (click)>، و <label for> للـ inputs. والـ overlays (dialog، menu) خدهم من Angular CDK عشان الـ focus trap والـ keyboard.
HTMLicon button done right
<button appButton variant="secondary" size="sm" type="button" (click)="copy()" [attr.aria-label]="'Copy answer'">
  <svg aria-hidden="true" class="size-4">…</svg>
  <span class="sr-only">Copy answer</span>
</button>
10

الأداء وحجم الـ CSS

Performance considerations
Basics

CSS الـ Tailwind في الإنتاج غالبًا عشرات الـ KB (مضغوط أقل بكتير) لأنه بيتولد للـ classes المستخدمة بس. اللي ممكن يكبّره: arbitrary values كتير، safelists ضخمة، أو scan لملفات مش محتاجها (monorepo). راقب حجم styles.css في الـ build budgets من Production Frontend، وخلي الخطوط (Cairo/Inter) font-display: swap و subset للأحرف المستخدمة — الخطوط العربية تقيلة وبتأثر على LCP أكتر من الـ CSS.

11

أخطاء شائعة

Common mistakes
Basics
  • Classes متركبة ديناميكيًا ('bg-' + color) فمش بتتولد.
  • Arbitrary values في كل حتة (mt-[17px]) بدل الـ scale.
  • Copy-paste لنفس الـ 20 class في كل مكان بدل component.
  • ml-/pr- في تطبيق عربي بدل logical utilities.
  • شيل الـ focus outline (outline-none) من غير focus-visible: بديل.
  • تثبيت Tailwind v4 بخطوات v3 (tailwind.config.js + autoprefixer + @tailwind directives).
12

اختبر فهمك

Knowledge check
Basics

تطبيق عربي/إنجليزي: الأيقونة لازم تبعد 8px عن بداية النص في الاتجاهين. الـ class الصح؟

13

تمارين محلولة

Worked exercises
Practical
1: Layout للـ chat في الـ Capstone: sidebar للمحادثات، منطقة رسائل، input ثابت تحت، ويتحول لعمود واحد على الموبايل
HTMLsolution
<div class="grid h-dvh grid-rows-[auto_1fr] md:grid-cols-[18rem_1fr] md:grid-rows-1">
  <aside class="hidden border-e border-gray-200 md:block dark:border-gray-800">…conversations…</aside>
  <main class="flex min-h-0 flex-col">
    <ol class="flex-1 space-y-4 overflow-y-auto p-4" aria-live="polite">…messages…</ol>
    <form class="sticky bottom-0 border-t border-gray-200 bg-white p-3 dark:border-gray-800 dark:bg-gray-900">…</form>
  </main>
</div>

نقط مهمة: min-h-0 عشان الـ overflow يشتغل جوه flex، border-e logical، aria-live عشان الـ screen readers تقرا الردود الجديدة، و h-dvh عشان شريط المتصفح على الموبايل.

2: نقل مشروع من Tailwind v3 لـ v4

الحل: اقرأ upgrade guide وشغّل الـ upgrade tool الرسمي، حوّل tailwind.config.js theme لـ @theme في CSS، بدّل الـ directives بـ @import "tailwindcss"، شيل autoprefixer، استخدم @tailwindcss/postcss، وراجع الـ classes اللي اتغير اسمها أو سلوكها (الـ upgrade guide فيه قائمة)، وبعدين visual regression على الصفحات الأساسية (screenshots بـ Playwright).

14

أسئلة إنترفيو

Interview questions
Basics
(Junior) إيه الـ utility-first CSS؟
إنك تبني الستايل من classes صغيرة كل واحدة بتعمل خاصية واحدة مباشرة في الـ markup، بدل ما تخترع أسماء semantic وتكتب CSS ليها في ملف منفصل.
(Mid) إزاي Tailwind بيخلي حجم الـ CSS صغير؟
بيعمل scan لملفات المشروع ويولّد CSS للـ classes المستخدمة فعلًا بس، من design tokens محددة، فمفيش CSS مش مستخدم بيوصل للإنتاج.
(Senior) الفريق مختلف: Tailwind ولا Angular Material؟
بقيّم على احتياجات المنتج: components معقدة accessible جاهزة (Material) مقابل تصميم مخصص (Tailwind + CDK)، مهارات الفريق، وجود design system. غالبًا الحل: tokens موحدة، Material/CDK للـ behaviour المعقد، و Tailwind للـ layout، مع قواعد مكتوبة (components بدل copy-paste، logical utilities، مفيش arbitrary values من غير سبب).
↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس