Tailwind CSS Colors in Svelte Projects

Learn how to use Tailwind CSS color utilities in Svelte components with reactive styling and stores.

sveltecomponentsreactivestores
intermediate8 min readtutorial

Tailwind Colors in Svelte Components

Svelte's concise syntax makes Tailwind integration straightforward. Apply color classes directly in markup and use reactive declarations for conditional styling.

Conditional Color Classes

<script>
  export let variant = 'default';
  const variants = {
    default: 'bg-slate-100 text-slate-800',
    primary: 'bg-blue-600 text-white',
    danger: 'bg-red-600 text-white',
    success: 'bg-emerald-600 text-white',
  };
  $: colorClass = variants[variant] || variants.default;
</script>

<button class="px-4 py-2 rounded-lg font-medium {colorClass}">
  <slot />
</button>

Theme Store Pattern

// stores/theme.js
import { writable } from 'svelte/store';

export const theme = writable('light');

theme.subscribe(value => {
  if (typeof document !== 'undefined') {
    document.documentElement.classList.toggle('dark', value === 'dark');
  }
});

Tips for Svelte and Tailwind

  • Use class: directive for toggling single classes like class:bg-blue-500={isActive}
  • Keep color mappings in objects so Tailwind can detect all class names at build time
  • Add './src/**/*.svelte' to Tailwind content configuration
  • Use Svelte stores for global theme state management

Frequently Asked Questions

Does Tailwind work with SvelteKit?

Yes. SvelteKit has official Tailwind integration. Run npx svelte-add@latest tailwindcss or configure it manually in your postcss.config.js.

Can I use Tailwind's dark mode with Svelte stores?

Yes. Create a writable store that toggles the dark class on the document element. Subscribe to the store to sync the DOM class with your state.

Try Our Color Tools

50+ free tools for Tailwind CSS developers. No signup required.

Explore Tools