Tailwind CSS Learning
A utility-first CSS framework for rapidly building modern websites
Installation
Tailwind CSS can be installed using multiple methods depending on your project setup. Below are the most common methods:
1. CDN (Quick Start)
Ideal for small projects or trying out Tailwind quickly.
<script src="https://cdn.tailwindcss.com"></script>
Then you can start using Tailwind classes directly in your HTML:
<button class="bg-blue-500 text-white px-4 py-2 rounded">Click Me</button>
2. NPM Installation
Use npm to install Tailwind in a more scalable setup.
# Create your project
npm init -y
# Install Tailwind
npm install -D tailwindcss
npx tailwindcss init
Create a tailwind.config.js
and set up your template paths:
// tailwind.config.js
module.exports = {
content: ["./*.html"],
theme: {
extend: {},
},
plugins: [],
}
3. PostCSS Configuration
For frameworks like Laravel, Vue, or React:
- Install Tailwind and PostCSS
- Create
postcss.config.js
andtailwind.config.js
- Import Tailwind in your CSS file:
/* styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
Then build the CSS using a tool like Vite, Webpack, or PostCSS CLI:
npx tailwindcss -i ./styles.css -o ./output.css --watch
Visual Reference:
Utility-First Concept
Tailwind CSS embraces a utility-first approach to styling. Instead of writing custom CSS, you apply utility classes directly to HTML elements. Each class does one job, such as setting margin, padding, color, or layout.
Traditional CSS Approach:
/* style.css */
.card {
background-color: #f3f4f6;
padding: 1rem;
border-radius: 0.5rem;
font-weight: bold;
}
<div class="card">This is a card</div>
Tailwind Utility Approach:
<div class="bg-gray-100 p-4 rounded-lg font-bold">
This is a card
</div>
This approach allows:
- Faster development
- Better consistency
- No need to switch between HTML & CSS files
- Easier refactoring
Visual Demo:
Responsive Design
Tailwind makes it simple to build responsive designs with mobile-first breakpoints. It includes five default breakpoints:
sm
: β₯ 640pxmd
: β₯ 768pxlg
: β₯ 1024pxxl
: β₯ 1280px2xl
: β₯ 1536px
How to Use
You can prefix utility classes with these breakpoints to apply styles only when the screen size matches or exceeds the breakpoint:
<div class="text-sm md:text-lg lg:text-xl">
Responsive Text
</div>
In the example above:
text-sm
applies on small screensmd:text-lg
kicks in at β₯768pxlg:text-xl
kicks in at β₯1024px
Visual Guide:
Typography
Tailwind CSS offers extensive typography utilities for customizing text appearance quickly. These utilities include:
- Text size:
text-sm
,text-base
,text-xl
,text-3xl
, etc. - Text color:
text-gray-700
,text-red-500
,text-green-600
, etc. - Font weight:
font-light
,font-bold
,font-extrabold
- Text alignment:
text-left
,text-center
,text-right
- Text transform:
uppercase
,lowercase
,capitalize
- Font style:
italic
,not-italic
- Line height:
leading-tight
,leading-relaxed
- Letter spacing:
tracking-tight
,tracking-wider
Example:
<p class="text-xl font-bold text-blue-600 text-center uppercase">
Tailwind Typography Example
</p>
Visual Demo:
Spacing & Layout
Tailwind CSS provides a comprehensive set of utility classes for controlling spacing and layout:
1. Margin and Padding
m-4
β Margin on all sidesmt-2
,mr-2
,mb-2
,ml-2
β Margin on individual sidesp-6
,px-4
,py-3
β Padding control
<div class="p-4 m-2 bg-gray-100">Box with spacing</div>
2. Grid Layout
Create responsive grids using grid
and grid-cols-*
utilities.
<div class="grid grid-cols-2 gap-4">
<div class="bg-blue-100 p-4">Column 1</div>
<div class="bg-blue-200 p-4">Column 2</div>
</div>
3. Flexbox Utilities
flex
,flex-col
,flex-row
justify-center
,items-center
gap-4
β Adds spacing between flex/grid items
<div class="flex justify-between items-center p-4 bg-gray-200">
<span>Left</span>
<span>Right</span>
</div>
4. Positioning
relative
,absolute
,fixed
top-0
,right-4
,z-50
Visual Demo:
Custom Components
Tailwind CSS encourages creating reusable components by combining utility classes into HTML structures. You can build UI elements like buttons, cards, alerts, and more without writing custom CSS.
Example: Button Component
<button class="bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded">
Primary Button
</button>
Example: Card Component
<div class="max-w-sm rounded overflow-hidden shadow-lg bg-white">
<img class="w-full" src="https://via.placeholder.com/400x200" alt="Image">
<div class="px-6 py-4">
<h3 class="font-bold text-xl mb-2">Card Title</h3>
<p class="text-gray-700 text-base">This is a reusable card component built with Tailwind.</p>
</div>
</div>
Tips for Component Reuse:
- Create components using HTML partials or includes (in Blade, EJS, etc.)
- Use @apply in custom CSS if you use Tailwind via PostCSS/SASS:
/* styles.css */
.btn-primary {
@apply bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded;
}
Visual Example:
Dark Mode
Tailwind CSS supports dark mode using either the media strategy (based on system preference) or the class strategy (manually toggled).
1. Enabling Dark Mode
Edit your tailwind.config.js
to use the class strategy:
// tailwind.config.js
module.exports = {
darkMode: 'class', // or 'media'
content: ["./*.html"],
theme: {
extend: {},
},
plugins: [],
}
2. Usage Example
<div class="bg-white text-black dark:bg-gray-900 dark:text-white p-6">
This box supports dark mode.
</div>
3. Toggling with JavaScript
// Toggle dark mode on button click
document.documentElement.classList.toggle('dark');
4. Best Practices
- Use
dark:
prefix for any utility class - Always test for readability and contrast in both modes
- Consider a toggle switch in your UI
Visual Example:
Transitions & Animations
Tailwind CSS includes utility classes for adding smooth transitions and animations to your UI elements.
1. Transition Utilities
transition
β Enable transitions on all propertiestransition-colors
,transition-opacity
β Apply to specific propertiesduration-300
,ease-in-out
,delay-200
β Customize timing
Example: Button Hover Effect
<button class="bg-blue-500 text-white px-4 py-2 rounded transition duration-300 hover:bg-blue-700">
Hover Me
</button>
2. Animation Utilities
Tailwind also includes a set of pre-built animations:
animate-spin
β Continuous rotationanimate-ping
β Pulsing effectanimate-bounce
β Bouncing up and downanimate-pulse
β Fading in and out
Example: Spinning Loader
<div class="animate-spin h-8 w-8 border-4 border-blue-500 border-t-transparent rounded-full"></div>
Visual Demo:
Forms
Tailwind CSS lets you style forms using utility classes, and you can enhance consistency using the @tailwindcss/forms plugin for better default styling.
1. Basic Input Styling
<input type="text" placeholder="Your Name"
class="border border-gray-300 rounded px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
2. Checkbox & Radio
<label class="inline-flex items-center">
<input type="checkbox" class="form-checkbox text-blue-600">
<span class="ml-2">Subscribe to newsletter</span>
</label>
3. Select Dropdown
<select class="border rounded px-4 py-2 focus:ring-2 focus:ring-green-400">
<option>Option 1</option>
<option>Option 2</option>
</select>
4. Textarea
<textarea rows="4" placeholder="Write something..."
class="w-full border rounded px-4 py-2 focus:ring-2 focus:ring-purple-500"></textarea>
5. Using the Forms Plugin
Install the official Tailwind CSS forms plugin:
npm install -D @tailwindcss/forms
Then add it to your tailwind.config.js
:
module.exports = {
plugins: [
require('@tailwindcss/forms'),
],
}
Visual Demo:
Plugins
Tailwind CSS supports official and community plugins to extend its functionality. Popular plugins include Typography, Forms, and Aspect Ratio.
1. Installing a Plugin
Install using npm and add to your tailwind.config.js
:
# Install
npm install -D @tailwindcss/forms @tailwindcss/typography @tailwindcss/aspect-ratio
// tailwind.config.js
module.exports = {
content: ["./*.html"],
theme: {
extend: {},
},
plugins: [
require('@tailwindcss/forms'),
require('@tailwindcss/typography'),
require('@tailwindcss/aspect-ratio'),
],
}
2. Forms Plugin
Improves base form styles automatically:
<input type="email" class="form-input" placeholder="you@example.com">
3. Typography Plugin
Provides pre-styled prose for content-heavy pages like blogs:
<article class="prose">
<h1>Blog Title</h1>
<p>This is a paragraph inside a beautifully styled article.</p>
</article>
4. Aspect Ratio Plugin
Maintain fixed aspect ratios for embedded content:
<div class="aspect-w-16 aspect-h-9">
<iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ" allowfullscreen></iframe>
</div>
Visual Demo:
Customization
Tailwind CSS allows deep customization through the tailwind.config.js
file. You can modify themes, extend colors, add spacing, and enable custom variants.
1. Basic Custom Theme
You can override or extend the default theme like this:
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
primary: '#1d4ed8',
secondary: '#9333ea',
},
spacing: {
'72': '18rem',
'84': '21rem',
},
fontFamily: {
sans: ['Inter', 'sans-serif'],
},
},
},
}
2. Add Custom Breakpoints
extend: {
screens: {
'xs': '480px',
},
}
3. Enable Variants
Customize which variants (like hover
, focus
, disabled
) are generated:
variants: {
extend: {
backgroundColor: ['active'],
opacity: ['disabled'],
},
}
4. Custom Utilities with Plugins
You can also add your own utilities using the plugin system:
plugins: [
function({ addUtilities }) {
const newUtilities = {
'.skew-10deg': {
transform: 'skewY(-10deg)',
},
}
addUtilities(newUtilities)
}
]
Visual Example:
State Variants
Tailwind CSS allows you to apply styles conditionally using pseudo-class variants. These variants help you style elements based on user interaction or element state.
Common Variants
hover:
β Styles when a user hovers over an elementfocus:
β Styles when an input or button is focusedactive:
β Styles when an element is being clickeddisabled:
β Styles for disabled buttons or inputsgroup-hover:
β Apply styles based on parent group hover
Examples
1. Hover Button
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
Hover Me
</button>
2. Focus Input
<input type="text" placeholder="Focus me"
class="border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 px-4 py-2 rounded">
3. Disabled Button
<button class="bg-gray-400 text-white font-bold py-2 px-4 rounded opacity-50 cursor-not-allowed" disabled>
Disabled
</button>
4. Active State
<button class="bg-green-500 active:bg-green-700 text-white py-2 px-4 rounded">
Press Me
</button>
5. Group Hover (Parent-Child Hover Effect)
<div class="group">
<p class="text-gray-500 group-hover:text-black">Hovering the parent changes my color</p>
</div>
Visual Demo
@apply & Custom Classes
Tailwind CSS supports the @apply
directive in your custom CSS files, allowing you to compose utility classes into your own reusable class names. This is useful for simplifying repeated styles and maintaining clean code.
1. How to Use @apply
Create a new CSS file (e.g., styles.css
) and import Tailwindβs layers:
/* styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
.btn-primary {
@apply bg-blue-600 text-white font-semibold px-4 py-2 rounded hover:bg-blue-700;
}
.card {
@apply p-6 bg-white rounded-lg shadow-md;
}
2. Example Usage in HTML
<button class="btn-primary">Click Me</button>
<div class="card">
<h3 class="text-xl font-bold mb-2">Card Title</h3>
<p>This is a custom card using @apply utilities.</p>
</div>
3. When to Use @apply
- To avoid repeating the same utility classes across multiple elements
- To create consistent design tokens like buttons, cards, alerts, etc.
- To keep HTML markup clean and readable
Important Notes:
@apply
only works within the Tailwind CSS build pipeline (requires PostCSS)- Not all utilities (like responsive variants) can be used with
@apply
Visual Reference:
Tailwind with JS Frameworks
Tailwind CSS integrates seamlessly with popular JavaScript and TypeScript frameworks. Whether you're using React, Vue, Angular, or Laravel Blade, you can build dynamic and modern UIs while benefiting from Tailwind's utility-first design.
1. Using Tailwind with React
Install via npm inside a Create React App or Vite project:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Update tailwind.config.js
:
module.exports = {
content: ["./src/**/*.{js,jsx,ts,tsx}"],
theme: {
extend: {},
},
plugins: [],
}
In your main CSS file (e.g., index.css
):
@tailwind base;
@tailwind components;
@tailwind utilities;
Use classes in JSX:
<button className="bg-blue-500 text-white py-2 px-4 rounded">
React Button
</button>
2. Using Tailwind with Vue
Same installation as React. In your Vue SFCs:
<template>
<div class="text-center text-lg font-bold">Hello Vue with Tailwind!</div>
</template>
3. Using Tailwind with Angular
After installing Tailwind, include it in styles.css
or styles.scss
and configure tailwind.config.js
:
content: ["./src/**/*.{html,ts}"]
Then use classes in Angular components:
<button class="bg-green-500 hover:bg-green-700 text-white py-2 px-4 rounded">
Angular Button
</button>
4. Tailwind with Laravel Blade
Tailwind can be included via Laravel Mix or Vite. In your Blade templates:
<div class="bg-gray-100 p-4 rounded shadow">
Laravel Blade + Tailwind
</div>
5. Other Frameworks
- Next.js β Configure via PostCSS in
next.config.js
- Nuxt.js β Use official Tailwind Nuxt module
- SvelteKit β Add Tailwind via PostCSS or UnoCSS plugins
Visual Demo:
Performance Optimization (PurgeCSS)
Tailwind CSS includes a built-in purge mechanism to remove unused styles from your final production build, drastically reducing file size and improving page load speed.
1. Why Optimization is Important
- Tailwind generates thousands of utility classes by default
- Unused classes can bloat the final CSS file
- Purging ensures your site loads faster with a smaller CSS footprint
2. How to Enable Purge
In your tailwind.config.js
file, define the paths to all of your template files:
module.exports = {
content: [
"./public/**/*.html",
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
3. How it Works
When you build your project using Tailwind CLI, Webpack, or Vite, the compiler scans your files for used class names. Any class not found is automatically removed.
npx tailwindcss -i ./src/input.css -o ./dist/output.css --minify
4. Best Practices
- Always verify purge paths include all your components and templates
- Use
safelist
in the config to preserve dynamically-generated class names - Keep your dev build unminified for debugging, but purge before deploying
5. Example Safelist
module.exports = {
content: ["./src/**/*.{html,js}"],
safelist: ['bg-red-500', 'text-center', /^btn-/],
}
Before & After Comparison
- Development CSS: ~3MB
- Production CSS (purged): ~50KB
Visual Reference:
Tailwind UI Libraries
Tailwind CSS has a growing ecosystem of libraries that help you build UI components faster and more efficiently. These libraries provide pre-styled components built using Tailwindβs utility classes, saving time without sacrificing customization.
1. DaisyUI
A popular Tailwind plugin that offers components like buttons, navbars, cards, modals, etc., with themes support.
npm install daisyui
Add it to tailwind.config.js
:
module.exports = {
plugins: [require('daisyui')],
}
Example:
<button class="btn btn-primary">Click Me</button>
2. Flowbite
Flowbite provides interactive components like modals, tabs, dropdowns, and tooltips powered by Tailwind and JavaScript.
npm install flowbite
Add to tailwind.config.js
content array:
content: [
"./node_modules/flowbite/**/*.js"
]
Example:
<button data-modal-target="myModal" class="bg-blue-600 text-white px-4 py-2 rounded">
Open Modal
</button>
3. Headless UI
Created by the Tailwind team, Headless UI offers unstyled, accessible components (like menus and dialogs) for React and Vue.
npm install @headlessui/react
Ideal for complete UI control with Tailwind styling.
Comparison Table
Library | Component Type | JavaScript | Themes |
---|---|---|---|
DaisyUI | Styled | No | Yes |
Flowbite | Styled + JS | Yes | Limited |
Headless UI | Unstyled | Yes | No |
Visual Reference:
Accessibility in Tailwind
Creating accessible web interfaces is a crucial aspect of modern development. Tailwind CSS encourages accessibility by providing utilities that support good practices out of the box.
1. Use Semantic HTML
Start with proper HTML5 tags like <header>
, <nav>
, <main>
, <section>
, and <footer>
to provide context to screen readers and assistive technologies.
2. Use ARIA Attributes
Tailwind doesn't restrict or replace ARIA. You can use it seamlessly with any element:
<button aria-label="Close menu">
<i class="fas fa-times"></i>
</button>
3. Color Contrast & Visibility
- Ensure text meets WCAG contrast guidelines
- Use
text-white bg-black
,text-gray-800 bg-yellow-200
, etc. - Tailwind provides
focus-visible
andoutline
utilities to indicate keyboard focus
Example: Accessible Button
<button class="bg-blue-600 text-white px-4 py-2 rounded focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-300" aria-label="Submit Form">
Submit
</button>
4. Visually Hidden Text
Use sr-only
to hide content visually but keep it accessible for screen readers:
<span class="sr-only">(current)</span>
5. Keyboard Navigation
Ensure all interactive elements are keyboard-navigable. Tailwind's focus utilities help highlight these states clearly.
Accessibility Checklist:
- β Use semantic HTML
- β Add ARIA roles & labels where needed
- β Maintain good color contrast
- β Include focus indicators using Tailwind
- β
Use
sr-only
for screen-reader-only text
Tip: Use tools like Lighthouse or axe DevTools to audit accessibility of your Tailwind-based project.
Practice Projects
Apply what you've learned by building real-world projects using Tailwind CSS. These hands-on exercises will reinforce your understanding of utility classes, layout design, responsiveness, and component structure.
-
1. Responsive Landing Page β Create a product or app introduction page with:
- Hero section with call-to-action
- Responsive navbar and footer
- Feature grid with icons
<section class="bg-gray-100 text-center py-12"> <h1 class="text-4xl font-bold mb-4">Welcome to Tailwind</h1> <p class="text-lg text-gray-600">Build fast and responsive UIs</p> </section>
-
2. Dashboard Layout β Admin or analytics interface using:
- Sidebar navigation with icons
- Content cards and charts
- Dark mode toggle
-
3. Portfolio / Resume Site β Personal website including:
- About section with image grid
- Project gallery using responsive cards
- Downloadable resume and contact form
-
4. Pricing Page with Cards β Highlight service tiers with:
- 3-column responsive layout
- Pricing badges and call-to-action buttons
- Hover effects and shadows for engagement
<div class="grid grid-cols-1 md:grid-cols-3 gap-6"> <div class="p-6 border rounded-lg text-center shadow"> <h3 class="text-xl font-bold">Basic</h3> <p class="text-2xl font-semibold">$9/mo</p> <button class="mt-4 bg-blue-500 text-white px-4 py-2 rounded">Choose Plan</button> </div> </div>
Bonus Tip: Host your projects on GitHub and deploy with Netlify or Vercel for a professional portfolio.