/

Using Tailwind CSS with Laravel: A Step-by-Step Guide

Using Tailwind CSS with Laravel: A Step-by-Step Guide

This tutorial is part of the Laravel Handbook. Download it from here

One powerful way to enhance the styling of your Laravel applications is by using Tailwind CSS. In this guide, we will walk you through the process of setting up and configuring Tailwind CSS with Laravel.

Let’s get started:

Step 1: Configuring Vite

The first thing we need to do is configure Vite to enable styling with Tailwind CSS. Open the terminal and run the following command:

1
npm install -D tailwindcss postcss autoprefixer

If you don’t have npm installed yet, make sure to install Node.js first.

This command will create a package.json file, a package-lock.json, and a node_modules folder.

Next, run the following command:

1
npx tailwindcss init -p

This will generate the tailwind.config.js and postcss.config.js files.

Note: If you are new to npx, check out my npx tutorial to learn more about it.

Now, open the tailwind.config.js file and add the following code:

1
2
3
4
5
6
7
8
/** @type {import('tailwindcss').Config} */
export default {
content: ['./resources/**/*.blade.php'],
theme: {
extend: {},
},
plugins: [],
};

In the resources/css/app.css file, add the following lines:

1
2
3
@tailwind base;
@tailwind components;
@tailwind utilities;

Finally, go back to the terminal and run npm run dev. Make sure to keep this command running while you develop your site, just like you would with php artisan serve.

Using Tailwind CSS with Laravel

Now that we have finished the setup process, we can start using Tailwind CSS in our Blade templates!

Step 2: Adding Tailwind CSS to Blade Templates

To start using Tailwind CSS in your Blade templates, add the following line to the <head> section of your HTML page:

1
2
3
4
5
6
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- @vite('resources/css/app.css') -->

When you refresh the page, you will notice an immediate change. Tailwind CSS adds a default normalization to your page, indicating that it is working correctly!

Now, you can add Tailwind CSS classes to your HTML body to style the page. For example:

1
2
3
<p class="font-bold border-b-gray-300 border-b pb-2 mb-3">
Test
</p>

Notice that any changes you make to the Blade template or the Tailwind CSS classes will automatically apply without refreshing the page. This is made possible by the magic of Vite and Laravel in development mode.

That’s it! You have successfully set up and configured Tailwind CSS with Laravel. Happy styling!

tags: [“Laravel”, “Tailwind CSS”, “CSS frameworks”, “web development”]