The user wants a design system in SvelteKit using Tailwind CSS and CSS variables for theming. This is a front-end development task.
-
Understand the Goal: Create a robust, scalable, and themeable design system using SvelteKit as the framework, Tailwind CSS for utility classes, and CSS variables for dynamic theming (e.g., dark mode, branding).
-
Key Components:
- SvelteKit: The project structure.
+layout.svelte, +page.svelte.
- Tailwind CSS: Configuration (
tailwind.config.js), extending the theme to use CSS variables.
- CSS Variables: Defining colors, spacing, typography in
app.css (or similar) and mapping them to Tailwind.
- Components: Atoms (Buttons, Inputs), Molecules (Cards).
- State Management/Context: Handling theme switching (light/dark/custom).
-
Step-by-Step Plan:
- Step 1: Setup: Initialize SvelteKit and install Tailwind CSS.
- Step 2: Tailwind Configuration: specific configuration to bridge CSS variables with Tailwind's utility classes. This is crucial. Instead of hardcoding colors in JS, reference
var(--color-primary).
- Step 3: Global Styles: Define the CSS variables in
:root for the default theme and [data-theme="dark"] (or similar) for alternative themes.
- Step 4: Theming Logic: Create a Svelte store or function to toggle the theme attribute on the
<html> or <body> tag.
- Step 5: Component Library: Build a few foundational components (Button, Card) to demonstrate the system.
- Step 6: Demo Page: Create a page to showcase the components and the theme switcher.
-
Drafting the Content - Technical Details:
- Installation:
npm create svelte@latest my-design-system, npm install -D tailwindcss postcss autoprefixer, npx tailwindcss init -p.
- Tailwind Config:
// tailwind.config.js
theme: {
extend: {
colors: {
primary: 'var(--color-primary)',
background: 'var(--color-background)',
// etc
}
}
}
- CSS File (
app.css):
:root {
--color-primary: #3b82f6;
--color-background: #ffffff;
}
[data-theme="dark"] {
--color-primary: #60a5fa;
--color-background: #0f172a;
}
- Theme Switcher: Needs to update
document.documentElement.dataset.theme.
-
Refining the Structure:
I will present this as a tutorial/guide with code snippets.
- Phase 1: Project Setup & Configuration.
- Phase 2: Defining Design Tokens (CSS Variables).
- Phase 3: Bridging Tailwind and CSS Variables.
- Phase 4: The Theme Switcher (Svelte Logic).
- Phase 5: Building UI Components.
- Phase 6: Implementation/Demo.
-
Self-Correction/Review during thought process:
- Initial thought: Should I use
class="dark" for dark mode?
- Correction: The prompt asks for "themeable", implying potentially more than just light/dark. Using
data-theme attributes is more semantic and flexible for multiple themes (e.g., "purple", "high-contrast") than Tailwind's built-in darkMode: 'class'. I will implement a generic data-theme approach but mention it handles dark easily.
- Tailwind Utility: Should I just write standard CSS or use
@apply?
- Decision: Use Tailwind utility classes in components for speed, but keep the definitions in CSS variables for flexibility.
-
Finalizing Code Snippets:
- tailwind.config.js: Needs to export
content locations correctly (./src/**/*.{html,js,svelte,ts}).
- app.html: Crucial to add a blocking script to prevent FOUC (Flash of Unstyled Content) if relying on local storage for theme preference, though simple toggling is fine for a demo. I'll keep it simple: just toggle the attribute.
- Components: Create a
Button.svelte that accepts variants using $props() (Svelte 5 runes) or standard export let (Svelte 4). I'll stick to standard syntax (Svelte 3/4) as it's universally understood right now, but maybe hint at Svelte 5 syntax if appropriate? No, stick to stable SvelteKit syntax for clarity.
-
Formatting: Use Markdown code blocks. Organize logically.
(Self-Correction on SvelteKit version): Ensure the syntax matches the current standard SvelteKit setup (Hooks in app.html or layout, routes in src/routes).
-
Constructing the Output: (Proceeds to generate the response based on these steps).
Here is a complete guide to building a robust, themeable design system in SvelteKit using Tailwind CSS and CSS Variables.
This approach allows you to use Tailwind's utility classes (like bg-primary) while dynamically changing the actual colors at runtime using CSS variables (no rebuild required).
Phase 1: Project Setup
First, set up the SvelteKit project and install Tailwind CSS.
npm create svelte@latest my-design-system
cd my-design-system
npm install
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Phase 2: Configuration
We need to tell Tailwind to scan our files and configure the theme to use CSS variables instead of hardcoded hex codes.
1. Configure tailwind.config.js
We will map Tailwind color names (like primary, surface) to CSS variable names (like --color-primary). The 255, 255, 255 syntax is a trick to allow Tailwind to generate opacity utilities (e.g., bg-primary/50) easily.
// tailwind.config.js
import { fontFamily } from 'tailwindcss/defaultTheme';
/** @type {import('tailwindcss').Config} */
export default {
content: ['./src/**/*.{html,js,svelte,ts}'],
theme: {
extend: {
colors: {
// Define semantic names mapped to CSS variables
primary: {
DEFAULT: 'rgb(var(--color-primary) / <alpha-value>)',
content: 'rgb(var(--color-primary-content) / <alpha-value>)',
},
surface: {
DEFAULT: 'rgb(var(--color-surface) / <alpha-value>)',
accent: 'rgb(var(--color-surface-accent) / <alpha-value>)',
},
base: {
DEFAULT: 'rgb(var(--color-base) / <alpha-value>)',
content: 'rgb(var(--color-base-content) / <alpha-value>)',
},
},
fontFamily: {
sans: ['Inter', ...fontFamily.sans],
},
},
},
plugins: [],
};
2. Create the Global Stylesheet
Create a file src/app.css. This is where we define the design tokens (variables). We define a :root for the default theme (Light) and a [data-theme="dark"] for the dark mode.
/* src/app.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
/*
Design Tokens
We use RGB values (0-255) split by spaces to support Tailwind opacity modifiers.
*/
:root {
/* Light Theme (Default) */
--color-primary: 79 70 229; /* Indigo */
--color-primary-content: 255 255 255; /* White text */
--color-surface: 255 255 255; /* White background */
--color-surface-accent: 243 244 246; /* Light Gray */
--color-base: 17 24 39; /* Slate 900 (Text color) */
--color-base-content: 255 255 255;
}
[data-theme="dark"] {
/* Dark Theme */
--color-primary: 129 140 248; /* Lighter Indigo */
--color-primary-content: 0 0 0; /* Black text */
--color-surface: 17 24 39; /* Slate 900 */
--color-surface-accent: 31 41 55; /* Slate 800 */
--color-base: 243 244 246; /* Light Gray (Text color) */
--color-base-content: 17 24 39;
}
/* Optional: Base body styles */
body {
@apply bg-surface text-base transition-colors duration-300;
}
3. Import the CSS
In your src/routes/+layout.svelte, import the CSS file.
<!-- src/routes/+layout.svelte -->
<script>
import '../app.css';
let { children } = $props();
</script>
<slot />
Phase 3: The Theme Engine
We need a way to persist the theme (so it doesn't flash on reload) and apply it to the HTML tag.
1. Create the Theme Store
Create src/lib/stores/theme.js. This store handles reading the user's preference and updating the data-theme attribute on the <html> element.
// src/lib/stores/theme.js
import { browser } from '$app/environment';
import { writable } from 'svelte/store';
const defaultValue = 'light';
const initialValue = browser ? (localStorage.getItem('theme') || defaultValue) : defaultValue;
export const theme = writable(initialValue);
export function toggleTheme() {
theme.update(current => {
const newTheme = current === 'light' ? 'dark' : 'light';
if (browser) {
localStorage.setItem('theme', newTheme);
document.documentElement.setAttribute('data-theme', newTheme);
}
return newTheme;
});
}
// Initialize theme on load
if (browser) {
document.documentElement.setAttribute('data-theme', initialValue);
}
2. Prevent Flash of Unstyled Content (FOUC)
To prevent the screen from flashing white when a user prefers dark mode, add a small script in src/app.html inside the <head> tag. This runs before Svelte hydrates.
<!-- src/app.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
<!-- Anti-FOUC Script -->
<script>
const theme = localStorage.getItem('theme');
if (theme) {
document.documentElement.setAttribute('data-theme', theme);
}
</script>
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
Phase 4: Building System Components
Now we build components using our new design tokens. Create a folder src/lib/components/.
1. Button Component (Button.svelte)
<!-- src/lib/components/Button.svelte -->
<script>
// Define props for variants
let { variant = 'solid', children } = $props();
</script>
<button
class="px-6 py-2 rounded-lg font-semibold transition-all duration-200
focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 focus:ring-offset-surface
{/* Variant Logic using Design System Colors */}
{variant === 'solid' ? 'bg-primary text-primary-content hover:opacity-90' : ''}
{variant === 'outline' ? 'border-2 border-primary text-primary hover:bg-primary hover:text-primary-content' : ''}
{variant === 'ghost' ? 'bg-transparent text-base hover:bg-surface-accent' : ''}"
>
{@render children()}
</button>
2. Card Component (Card.svelte)
<!-- src/lib/components/Card.svelte -->
<script>
let { title, children } = $props();
</script>
<div class="bg-surface border border-surface-accent rounded-xl shadow-lg p-6 space-y-4
hover:shadow-xl transition-shadow duration-300">
<h3 class="text-lg font-bold text-base">{title}</h3>
<div class="text-base opacity-80">
{@render children()}
</div>
</div>
3. Theme Toggle (ThemeToggle.svelte)
<!-- src/lib/components/ThemeToggle.svelte -->
<script>
import { theme, toggleTheme } from '$lib/stores/theme.js';
// Icons (using simple SVGs)
const SunIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" d="M12 3v2.25m6.364.386l-1.591 1.591M21 12h-2.25m-.386 6.364l-1.591-1.591M12 18.75V21m-4.773-4.227l-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0z" /></svg>`;
const MoonIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" d="M21.752 15.002A9.718 9.718 0 0118 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 003 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 009.002-5.998z" /></svg>`;
</script>
<button
onclick={toggleTheme}
class="p-2 rounded-full bg-surface-accent hover:bg-primary hover:text-primary-content transition-colors"
aria-label="Toggle theme"
>
{#if $theme === 'light'}
{@html MoonIcon}
{:else}
{@html SunIcon}
{/if}
</button>
Phase 5: Implementation
Finally, assemble the design system in your main page.
<!-- src/routes/+page.svelte -->
<script>
import Button from '$lib/components/Button.svelte';
import Card from '$lib/components/Card.svelte';
import ThemeToggle from '$lib/components/ThemeToggle.svelte';
</script>
<div class="min-h-screen p-8 flex flex-col items-center justify-center gap-8">
<div class="flex justify-between w-full max-w-2xl items-center mb-4">
<h1 class="text-3xl font-bold text-base">Design System</h1>
<ThemeToggle />
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 max-w-2xl w-full">
<!-- Color Usage -->
<Card title="Colors">
<p class="mb-4">Using semantic tokens allows dynamic theming.</p>
<div class="flex gap-2">
<div class="w-10 h-10 rounded bg-primary"></div>
<div class="w-10 h-10 rounded bg-surface-accent border"></div>
<div class="w-10 h-10 rounded bg-base text-surface flex items-center justify-center">Aa</div>
</div>
</Card>
<!-- Button Variants -->
<Card title="Buttons">
<div class="flex flex-wrap gap-4">
<Button variant="solid">Solid</Button>
<Button variant="outline">Outline</Button>
<Button variant="ghost">Ghost</Button>
</div>
</Card>
</div>
</div>
Summary of Architecture
- Tailwind Config: Acts as the mapper. It tells
bg-primary to look for the CSS variable --color-primary.
- App.css: Acts as the value provider. It defines what
--color-primary actually is (e.g., Blue in light mode, Light Blue in dark mode).
- Svelte Components: Are "color agnostic". They use classes like
bg-primary but don't know the specific hex codes.
- Theme Store: Handles the user preference and updates the
data-theme attribute on the HTML tag, which cascades the variable changes instantly to the entire app.