Set Up SvelteKit With Tailwind CSS
Published Oct 12, 2022
Table of Contents
Using Svelte Add
The easiest way to set up Tailwind CSS inside of an existing SvelteKit project is with svelte-add.
npx svelte-add@latest tailwindcss
Youβre done! π
This creates a app.postcss
file which is imported inside the root layout.
<script>
import '../app.postcss'
</script>
<slot />
Automatic Class Sorting With Prettier
Make sure you have the Prettier extension installed and itβs the default formatter in your VS Code settings.
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
Skip this step if you have prettier
in your project.
npm i -D prettier prettier-plugin-svelte
Install the Prettier plugin for Tailwind CSS.
npm i -D prettier-plugin-tailwindcss
After you save it should sort the classes.
<!-- Before -->
<button class="text-white px-4 sm:px-8 py-2 sm:py-3 bg-sky-700 hover:bg-sky-800">
...
</button>
<!-- After -->
<button class="bg-sky-700 px-4 py-2 text-white hover:bg-sky-800 sm:px-8 sm:py-3">
...
</button>
Useful Tailwind CSS Tips
Here are some useful quality of life tips when using Tailwind:
- If you need a Svelte component library you can use Skeleton, Flowbite Svelte or something more framework agnostic like daisyUI
- Use the Tailwind CSS IntelliSense extension to help you with autocomplete
- Use the Tailwind CSS Cheat Sheet to find what you need at a glance
- Avoid using
@apply
and abstract long class names inside a variable if you want to reuse them - Enable word wrap in your editor with Alt + Z to make it easier to work with long class names