Style Svelte Components
Notes on styling Svelte with Tailwind.
Using CSS (Component-scoped)
Svelte components bundle markup, styles, and behavior. Styles are scoped by default,
so they apply only to the component and don’t leak out. By default, a Svelte
component is styled with a single <style> tag containing CSS rules.
<script>
let title = 'Hello Svelte';
</script>
<h1>{title}</h1>
<style>
h1 {
font-size: 1.5rem;
font-weight: 700;
color: #3b82f6;
}
</style> Using Tailwind CSS
When you use Tailwind CSS inside a .svelte component, you’re writing utility
classes directly in the markup rather than writing CSS inside the component’s <style> block.
<script>
let title = 'Hello Svelte';
</script>
<h1 class="text-2xl font-bold text-blue-500">
{title}
</h1> In this blog, we’ll look at how to style Svelte apps with Tailwind CSS.
Conditional Styling
Adding or removing a class based on a condition is a common pattern in UI development. In Svelte, there are several ways to do this. Consider the sample program below, and then let’s explore the different approaches.
Sample Program :
src/routes/+page.svelte
<script>
const paragraph = "The quick brown fox jumps over the lazy dog.";
let typed = $state("");
let active = $state(false);
let chars = $derived(paragraph.split(""));
let typedChars = $derived(typed.split(""));
let currentIndex = $derived(typedChars.length);
function handleKeydown(e) {
if (!active) return;
if (e.key.length === 1) {
e.preventDefault(); // Prevent scrolling
typed += e.key;
} else if (e.key === "Backspace") {
typed = typed.slice(0, -1);
}
}
</script>
<svelte:window on:keydown={handleKeydown} />
<div class="flex flex-wrap py-4">
{#each chars as char, i (i)}
<span
class="text-xl transition-all duration-100 ease-in text-gray-400
{active && i === currentIndex
? 'bg-[#ffcb56] text-gray-900' // cursor
: typedChars[i] === char
? 'text-green-400' // correct
: typedChars[i] && typedChars[i] !== char
? char != ' '
? 'text-red-400' // incorrect letter
: 'bg-red-400' // incorrect space
: !typedChars[i] && !active && ''}"
>
{char === " " ? " " : char}
</span>
{/each}
</div>
<button
class="rounded-lg p-2 cursor-pointer border border-blue-400 text-blue-400 hover:text-gray-900 hover:bg-blue-400"
onclick={() => {
active = !active;
typed = "";
}}
>
{active ? "End Typing" : "Start Typing"}
</button> Output :
1. Using Ternary Operators
<span
class={`text-xl transition-all duration-100 ease-in text-gray-400 ${
active && i === currentIndex
? "bg-[#ffcb56] text-gray-900" // cursor
: typedChars[i] === char
? "text-green-400" // correct
: typedChars[i] && typedChars[i] !== char
? char !== " "
? "text-red-400" // incorrect letter
: "bg-red-400" // incorrect space
: ""
}`}
>
{char === " " ? " " : char}
</span> In the program above, text styling is applied conditionally using template literals and nested ternary operators. While ternary operators work well for simple conditions, they quickly become verbose and difficult to read when nested, making them a poor choice for complex conditional styling.
Since Svelte 5.16, class can be an object or array, and is converted to a string using clsx.
2. Passing an Object
<span
class={{
"text-xl transition-all duration-100 ease-in text-gray-400": true, // always
"bg-[#ffcb56] text-gray-900": active && i === currentIndex, // cursor
"text-green-400": typedChars[i] === char, // correct
"text-red-400": typedChars[i] && typedChars[i] !== char && char !== " ", // incorrect letter
"bg-red-400": typedChars[i] && typedChars[i] !== char && char === " ", // incorrect space
}}
>
{char === " " ? " " : char}
</span> If the value is an object, the truthy keys are added.
In the program above, CSS classes are applied conditionally using an object passed to the class attribute. Each key represents a CSS class, while its value determines whether that class is applied. This approach avoids nested ternary operators and keeps conditional styling readable and easy to maintain.
3. Passing an Array
<span
class={[
"text-xl transition-all duration-100 ease-in text-gray-400", // always
active && i === currentIndex && "bg-[#ffcb56] text-gray-900", // cursor
typedChars[i] === char && "text-green-400", // correct
typedChars[i] && typedChars[i] !== char && char !== " " && "text-red-400", // incorrect letter
typedChars[i] && typedChars[i] !== char && char === " " && "bg-red-400", // incorrect space
]}
>
{char === " " ? " " : char}
</span> If the value is an array, the truthy values are combined.
In the program above, CSS classes are applied using an array passed to the class attribute. Each array element can contain a class name or a conditional expression that evaluates to a class name or a falsy value. Svelte automatically handles these values, making conditional styling concise and readable without nested ternary operators.
I like this since it reads like a collection of if this, then that statements.
Class Directives (Not Recommended)
<span
class="text-xl transition-all duration-100 ease-in text-gray-400"
class:bg-[#ffcb56]={active && i === currentIndex}
class:text-gray-900={active && i === currentIndex}
class:text-green-400={typedChars[i] === char}
class:text-red-400={typedChars[i] && typedChars[i] !== char && char !== " "}
class:bg-red-400={typedChars[i] && typedChars[i] !== char && char === " "}
>
{char === " " ? " " : char}
</span> Besides the approaches discussed above, we can also achieve the same using a class: directive, which was once a convenient way to set classes on elements
conditionally. However, It’s no longer recommended.
Style Child Component
Often, you need to influence the styles inside a child component. In Svelte, you can do this by passing classes as props or using CSS variables, allowing the parent to control the styling.
1. Passing classes as prop
With this method, you can easily pass Tailwind utility classes to style a child component as you like. However, because Tailwind doesn’t support constructing dynamic classes, this approach has its limitations.
Sample Program :
$lib/components/Button.svelte
<script>
let props = $props();
</script>
<button {...props} class={["rounded-xl border p-2 shadow", props.class]}>
{@render props.children?.()}
</button> src/routes/+page.svelte
<script>
import Button from "$lib/components/Button.svelte";
</script>
<Button class={["border-red-400 bg-red-200 text-red-800"]}>Primary</Button>
<Button class={["border-sky-400 bg-sky-200 text-sky-800"]}>Secondary</Button> Output :
2. Passing CSS Variables
With this method, you can pass CSS custom properties to a child component, making it easy to style elements dynamically. Unlike Tailwind classes, CSS variables can be computed on the fly.
Sample Program :
$lib/components/Box.svelte
<div class="box"></div>
<style>
.box {
width: 5em;
height: 5em;
background-color: var(--bg-color, #dcdcdc);
transition: background-color 1s ease;
}
</style> src/routes/+page.svelte
<script>
import Box from "$lib/components/Box.svelte";
function randomPastel() {
const hue = Math.floor(Math.random() * 360); // random hue
const saturation = Math.floor(Math.random() * 20 + 80); // 80–100% for bright pastel
const lightness = Math.floor(Math.random() * 15 + 75); // 75–90% for soft bright color
return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
}
</script>
<div class="my-2 flex flex-row gap-2">
<Box --bg-color={randomPastel()} />
<Box --bg-color={randomPastel()} />
<Box --bg-color={randomPastel()} />
<Box --bg-color={randomPastel()} />
</div> Output :
Custom Animations
In Tailwind, you can’t directly define custom animations inside it.
1. Component Scoped
If the animation is only needed for a single component and won’t be reused
elsewhere, we can define it inside that component’s <style> tag.
Sample Program :
src/routes/+page.svelte
<script>
let balloon = "🎈";
</script>
<div
class="relative h-[200px] w-full overflow-hidden rounded-md bg-gradient-to-t from-white to-sky-300"
>
<p
class="animate-float absolute -bottom-1/2 left-1/2 -translate-x-1/2 text-[2.5rem]"
>
{balloon}
</p>
</div>
<style>
@keyframes float {
0% {
transform: translate(-50%, 100px) rotate(0deg);
}
50% {
transform: translate(-50%, -100px) rotate(3deg);
}
100% {
transform: translate(-50%, -300px) rotate(-3deg);
}
}
.animate-float {
animation: float 6s ease-in-out infinite;
}
</style> 2. Global : Outside the Component
If the animation should be shared across multiple components, we can define it
in layout.css (or another global stylesheet) so it can be reused anywhere.
Sample Program :
src/layout.css
@import "tailwindcss";
@plugin '@tailwindcss/typography';
@theme {
--animate-float: float-up 6s ease-in-out infinite;
@keyframes float-up {
0% {
transform: translate(-50%, 100px) rotate(0deg);
}
50% {
transform: translate(-50%, -100px) rotate(3deg);
}
100% {
transform: translate(-50%, -300px) rotate(-3deg);
}
}
} src/routes/+page.svelte
<script>
let balloon = '🎈';
</script>
<div
class="relative h-[200px] w-full overflow-hidden rounded-md bg-gradient-to-t from-white to-sky-300"
>
<p class="animate-float absolute -bottom-1/2 left-1/2 -translate-x-1/2 text-[2.5rem]">
{balloon}
</p>
</div> Output :
🎈
That’s all folks.
Svelte and Tailwind play really well together. You get scoped styles by default, utility-driven styling, and the freedom to fall back on CSS variables or custom animations whenever you need more fine-grained control.
> cd ..