How to Add Tailwind CSS to HTML ?
Last Updated :
12 Mar, 2024
Tailwind CSS is a utility-first CSS framework that provides a set of pre-defined classes to help you quickly style your HTML elements. It’s known for its flexibility and ease of customization. In this article, we will explore different approaches to adding Tailwind CSS to your HTML projects.
Add Tailwind CSS to HTML using a CDN Link
The quickest way to start using Tailwind CSS is by adding a link to the Tailwind CSS CDN in the <head> section of your HTML file. This method is suitable for small projects or for trying out Tailwind CSS.
HTML<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Tailwind CSS Example</title>
<link href=
"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"
rel="stylesheet">
</head>
<body>
<h1 class="text-3xl font-bold underline text-green-600">
Welcome to GeeksforGeeks
</h1>
</body>
</html>
Output:
In this example, the Tailwind CSS CDN link is added to the <head>
section, and Tailwind utility classes are used to style the <h1>
element.
Add Tailwind CSS to HTML using npm for a Custom Build
For larger projects or when you need to customize Tailwind CSS, it’s recommended to install Tailwind CSS via npm and set up a build process.
Step 1: Initialize npm
Create a new directory for your project and initialize npm:
mkdir tailwind-project
cd tailwind-project
npm init -y
Step 2: Install Tailwind CSS
Install Tailwind CSS and its dependencies:
npm install -D tailwindcss postcss autoprefixer
Step 3: Generate Tailwind Configuration
Generate the tailwind.config.js
and postcss.config.js
files:
npx tailwindcss init -p
Step 4: Create your CSS file
Create a styles.css
file in your project directory and add the Tailwind directives:
/* styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
Step 5: Build your CSS
Add a build script to your package.json
file:
"scripts": {
"build": "tailwindcss -i ./styles.css -o ./dist/output.css --watch"
}
Run the build script to generate your output.css
file:
npm run build
Step 6: Link the CSS in your HTML
Link the generated output.css
file in your HTML file:
Javascript<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Tailwind CSS Example</title>
<link href="./dist/output.css" rel="stylesheet">
</head>
<body>
<h1 class="text-3xl font-bold underline text-green-600">
Welcome to GeeksforGeeks
</h1>
</body>
</html>
Output:
Adding Tailwind CSS to your HTML project can be done quickly using a CDN for simple use cases, or through a custom build process using npm for more advanced scenarios and customization.
Share your thoughts in the comments
Please Login to comment...