SvelteKit - Tailwind CSS Setup

SvelteKit - Tailwind CSS Setup

Introduction

Hello and welcome back to my series of technical blog posts on SvelteKit! In this post, I will be introducing my next topic which is integrating Tailwind CSS with SvelteKit.

Tailwind CSS is a utility-first CSS framework that provides a set of pre-defined CSS classes that can be used to style HTML elements. It allows you to create complex layouts and designs with minimal CSS code, making it a popular choice among developers.

Integrating TailwindCSS with SvelteKit can help streamline your development process by providing pre-defined styles that can be easily applied to your components.

Install Tailwind CCS

To install Tailwind CSS and its dependencies, navigate to your SvelteKit project directory in your terminal and run the following command:

pnpm install -D tailwindcss postcss autoprefixer @tailwindcss/forms

This command will install the latest version of TailwindCSS, PostCSS, Autoprefixer and Tailwind Forms as dev dependencies in your project.

Configure Tailwind CSS

Next, we need to create a configuration file for TailwindCSS. You can do this by running the following command in the root of our project directory:

pnpx tailwindcss init tailwind.config.cjs -p

This command will generate a default tailwind.config.cjs file in your project root. The -p flag tells Tailwind CSS to generate a basic postcss.config.cjs file.

Now add the file paths to the Svelte template files in tailwind.config.cjs :

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ['./src/**/*.{html,js,svelte,ts}'],
  theme: {
    extend: {},
  },
  plugins: [require("@tailwindcss/forms")],
}

Add Tailwind to our CSS

Create a src/app.css file and add Tailwind:

@tailwind base;
@tailwind components;
@tailwind utilities;

Then add src/app.css to our layout file src/routes/+layout.svelte:

<script>
  import "../app.css";
</script>

<slot />

Use Tailwind

We are now ready to sprinkle some Tailwind magic, for example on the main page:

<div class="mx-auto max-w-2xl text-center p-16">
  <h1 class="text-4xl font-bold text-gray-900">Top 3</h1>

  <div class="mt-8">
    {#if data.todos.length > 0}
      <Todos todos={data.todos} />
    {:else}
      <NewTop3 />
    {/if}
  </div>
</div>

Check out all the code in the GitHub Repository to see how I've styled the other Svelte components. Thanks for reading!