Tailwind CSS

In this module, we're going to cover how to add Tailwind to our SvelteKit project.
Table of Contents
Tailwind CSSView the code for this module.
Course Version History
  • Nov. 21, 2022 - Updated to SvelteKit v1.0.0-next.549. Changed __layout.svelte to +layout.svelte.

Let's install Tailwind CSS for styling. First, head over to the SvelteKit Framework Guide in the Tailwind docs. Things are constantly changing, so while these are the steps at the time of this recording, make sure you check the docs in case they change.

We can skip this first step since we've already created our SvelteKit app, and move on to copying the following commands and running them in our terminal.

npm install -D tailwindcss postcss autoprefixer svelte-preprocess npx
tailwindcss init tailwind.config.cjs -p
mv postcss.config.js postcss.config.cjs

This first command will install Tailwind, and the others will generate two files, **tailwind.config.cjs**and postcss.config.cjs.

If you open up the code in your text editor, you'll see that tailwind is installed, and the two new files have been generated. Our postccs.config.js file is where we can specify what PostCSS plugins we want to use. All we need to do is export an object that contains a key called plugins, which is an array of plugins that should be used to process our CSS. We need to require Tailwind CSS since of course we want to use Tailwind as well as autoprefixer, so we can automatically add vendor prefixes to our CSS, but this has already been done for us, so we don't need to touch this file.

module.exports = {
  plugins: {
    autoprefixer: {},
    tailwindcss: {},

We can skip over step three. Next, let's move into our tailwind.config.cjs file where we need to add the paths to all of our templates. We can just copy and paste this code into the file.

module.exports = {
  content: ['./src/**/*.{html,js,svelte,ts}'],
  theme: {
    extend: {},
  plugins: [],

Finally, we need to add the @tailwind directives for each of Tailwind's layers in our app.css and make sure we are importing this file in +layout.svelte.

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

Now we can just re-start our app and tailwind should kick in! If you run the app locally in your browser, you will see tailwind is working because it has stripped all default element stylings. If you try adding some tailwind classes to your app, you should see the app update instantly in the browser with these changes.

Now that we've got tailwind installed, we will use it to build out the rest of our UI in future videos. Next up we're going to learn about working with Svelte components.