Unicorn Platform

World's best and simplest website builder powered by AI

Build your website
Tuesday, October 24, 2023

Learn Tailwind CSS in 7 Days

Introduction

Tailwind CSS has exploded in popularity as a utility-first framework for rapidly building modern, responsive web interfaces without battling stacked CSS specificity.

Compared to traditional CSS frameworks like Bootstrap, Tailwind avoids opinionated pre-designed components in favor of customizable low-level utility classes. This gives developers complete flexible control while eliminating the need to write custom CSS.

In this comprehensive 7 day guide, you'll learn how to start mastering Tailwind CSS the easy way. We'll cover core concepts, real-world examples, customization techniques, advanced features, and best practices.

By the end of this hands-on journey, you'll have the skills to build beautiful, fast websites entirely with Tailwind. Let's dive in!

Day 1 - Tailwind Fundamentals

Tailwind CSS is a utility-first framework that allows you to customize designs faster without writing custom CSS. Instead of bloated pre-styled components, Tailwind provides low-level utility classes for flexible styling based on constraints.

For example, instead of predefined .btn styles, Tailwind offers classes like px-4 py-2 font-bold rounded bg-blue-500 text-white. This gives you the building blocks to construct any UI without battling specificity.

Tailwind generates highly reusable CSS automatically based on the classes present in your HTML. It has variants for responsive design, accessibility, dark mode, interactions like hover, and more.

Compared to Bootstrap's pre-packaged components, Tailwind sticks to custom utilities that integrate cleanly with your own CSS. This customizable approach speeds up development while keeping your final stylesheet lean.

Installing Tailwind

Getting started with Tailwind is straightforward:

npm install tailwindcss

Next, generate a default config file:

npx tailwindcss init

Include Tailwind directives in your CSS:

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

Add Tailwind as a PostCSS plugin:

module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer'),    
  ] 
}

Run your build process and Tailwind will generate CSS based on your HTML classes.

For step-by-step installation guides, see the official documentation. Stick to the docs to avoid common pitfalls.

Tailwind Classes

Instead of global stylesheets, Tailwind uses utility classes for styling:

<div class="p-6 mx-auto bg-gray-200 rounded-lg md:p-8">
  <!-- Component -->  
</div>

Spacing, sizing, typography, color, layout, and many other utilities compose together to build any component without custom CSS:

<button
  class="px-5 py-3 text-sm font-medium tracking-wide text-white capitalize transition-colors duration-200 transform bg-blue-600 rounded-lg hover:bg-blue-500 focus:outline-none focus:ring focus:ring-blue-300 focus:ring-opacity-50">
  Submit
</button>

This declarative approach lets you construct UIs faster while avoiding specificity issues.

When structuring your HTML, put classes on semantic elements for accessibility:

<button class="...">
  <span class="...">Submit</span> 
</button>

Tailwind's utilities generate reusable CSS instead of rewriting duplicate rules.

Responsive Design

Tailwind makes building responsive interfaces simple with variants for different viewport sizes:

<div class="mt-4 sm:mt-0">...</div>

You can customize or extend breakpoints in Tailwind's configuration:

module.exports = {
  theme: {
    screens: {
      'sm': '640px',
      // ...
    }
  }
}

Mobile-first styles keep your CSS lean by adding modifiers only where needed. This avoids unnecessary media queries.

For optimal responsive design, use relative units like rem and em for component sizing. Tailwind's preset font-sizes and spacing scale well across breakpoints.

For example, [CompanyName]'s website (link) gracefully adapts its layout with Tailwind's responsive utilities for beautiful results across devices.

Customizing Tailwind

One of Tailwind's best features is customization. The config file allows custom fonts, colors, spacing values, variants, and more:

module.exports = {
  theme: {
    fontFamily: {
      display: ['Inter', sans-serif],
    },
    extend: {
      colors: {
        'brand': '#FF6363'
      }
    }
  }
}

You can then apply these values in your HTML:

<h1 class="text-4xl font-display">...</h1> 

<button class="bg-brand-500">...</button>

Extend default variants like responsive hover classes:

module.exports = {
  variants: {
    extend: {
      backgroundColor: ['hover', 'focus'],
    }
  }
}

Tailwind removes unused styles for optimal performance. Customize thoughtfully based on your project's needs.

Day 2 - Tailwind Components

Tailwind speeds up development by letting you build reusable UI components with utility classes instead of custom CSS.

Real-world examples include navigation, buttons, forms, cards, modals, and more. The composable classes handle layout, positioning, styling, and interactions.

When designing component APIs in Tailwind, opt for consistency and flexibility:

<!-- Good -->
<Navbar>
  <NavbarLink>Home</NavbarLink>
</Navbar>

<!-- Not ideal -->  
<Nav>
  <NavItem>Home</NavItem> 
</Nav>

Use variants to implement component states like .btn-primary, .btn-success, .btn-loading without new CSS rules.

Compared to frameworks like Bootstrap, Tailwind provides unlimited composability while maintaining semantic HTML. Let's walk through some component examples.

Building a navbar in Tailwind is straightforward with Flexbox utilities:

<nav class="relative bg-white flex flex-wrap items-center justify-between px-2 py-3">
  <!-- Nav content -->
</nav> 

Use responsive modifiers to adapt the layout:

<nav class="sm:flex-row flex-col flex-wrap">
  <!-- Links stacked on small screens -->
</nav>

Features like dropdowns, toggles, and menus use just markup and utility classes - no custom JavaScript required.

For multi-column navbars, leverage the grid system:

<nav class="grid grid-flow-col">
  <div class="col-start-1 col-end-3">Left part</div>
  <div class="col-start-3 col-end-4">Right part</div>
</nav>

Float UI's responsive navbar demonstrates these principles in action.

Buttons

Style buttons of any size using utilities like px, py, text-xs text-lg:

<button class="px-4 py-2 text-sm">
  Small button
</button>

<button class="px-6 py-3 text-base">
  Default button   
</button>

<button class="px-8 py-4 text-lg">
  Large button
</button> 

For loading and disabled states, use opacity and pointer-events:

<button
  class="opacity-50 cursor-not-allowed">
  Disabled
</button>

<button  
  class="opacity-75 cursor-wait">
  <svg class="animate-spin mr-3">...</svg>
  Loading
</button>

Group buttons together horizontally with Flexbox:

<div class="flex">
  <button class="btn">Save</button>
  <button class="btn ml-4">Cancel</button>
</div>

Tailwind provides unlimited button customization beyond basic presets.

Forms

Style inputs, labels, selects, textareas, and more with utilities:

<label class="block font-medium text-gray-700">Name</label>

<input class="border p-2 rounded w-full" />

Arrange form elements using Grid and Flexbox layouts:

<form class="grid grid-cols-4 gap-4">
  <div class="col-span-2">
    <input type="text"/>
  </div>
  
  <div class="col-span-2">
    <input type="email" />
  </div> 
</form>

Tailwind generates accessible styling for elements out of the box. Customize interactions with utilities for focus, hover, disabled, etc.

For multi-step forms, use CSS siblings and transitions:

<form class="steps">
  <fieldset class="step">...</fieldset> 
  <fieldset class="step">...</fieldset>
</form>

Then transition between them:

.step {
  transition: all 0.3s ease-out; 
}

.step:not(.active) {
  display: none;
} 

Cards

Cards demonstrate layout components in Tailwind using Flexbox and Grid utilities:

<div class="flex">
  <div class="rounded bg-white p-4 flex-1">
    <!-- Card content -->
  </div>
</div>

Extract into reusable card components:

<!-- Card.js -->
<div class="bg-white rounded {$props.className}">

  <header class="p-4">
    <h3>{$props.title}</h3>
  </header>
  
  <div class="p-4">
    {$props.children} 
  </div>

  <footer class="p-4 text-sm">
    {$props.footerText}
  </footer>

</div>

Use it anywhere:

<Card
  title="Card title"
  footerText="Footer text" 
>
  <!-- Content -->
</Card>

Make cards responsive with hidden and block. Group them horizontally, vertically, or in a grid.

Day 3 - Tailwind Templates

While components abstract repeated UI patterns, templates provide complete page layouts out of the box.

Tailwind templates include all the HTML and utility classes needed for common pages like:

  • Homepages
  • About pages
  • Contact pages
  • Blog layouts
  • Admin dashboards
  • Landing pages

The benefit of templates is they give you full-page examples to start from. You can then customize and slot in components modularly.

Compared to traditional templates and themes, Tailwind keeps things flexible without opinionated styles. Let's build some templates.

Page Templates

Home, about, contact, and other standard pages share common sections you can abstract into reusable templates:

<!-- PageTemplate.js -->
<Layout>

  <header>
    <Navbar />
  </header>

  <main class="p-6 md:p-8 max-w-3xl mx-auto">
    {$props.children} 
  </main>

  <footer>
    <Footer /> 
  </footer>
  
</Layout>

Then extend it for specific pages:

// Homepage
<PageTemplate>
  
  <HeroSection />
  
  <FeatureSection />
  
</PageTemplate>

This keeps your CSS lean by reusing layout utilities.

Making the templates fully responsive is straightforward with Tailwind's breakpoints. No media queries needed.

Landing Pages

Landing pages optimize conversions with sections like:

  • Eye-catching hero sections
  • Benefit-focused content
  • Prominent calls-to-action
  • Email signup forms
  • Social proof elements

Style these in Tailwind by composing reusable utility classes into landing page sections:

<!-- Hero section -->
<section class="py-20 px-6 bg-indigo-600 md:py-40">
  <div class="text-center mx-auto max-w-3xl">
    <h1 class="text-4xl font-bold text-white">...</h1>
    
    <p class="mt-6 text-xl text-indigo-100">...</p>
    
    <button class="bg-white font-medium mt-8">Get Started</button>
  </div>
</section>

Optimize conversions with A/B testing different headlines, colors, and calls to action.

Dashboard Templates

Admin dashboards need complex layouts including:

  • Side navigation
  • Datatables
  • Charts and graphs
  • User management UI

Grid and Flexbox utilities make this achievable:

<main class="grid grid-cols-4 gap-6">

  <aside class="col-span-1 bg-gray-100 p-6">
    <!-- Side nav -->
  </aside>

  <section class="col-span-3 p-6">
    <!-- Main content -->
  </section>
  
</main>

Tailwind alleviates dashboard template pain. See Float UI's admin templates for examples.

Converting Designs to Tailwind

For converting PSD or Sketch designs to Tailwind:

  • Analyze the design and plan your markup
  • Breakdown elements into required utilities
  • Build components for repeating patterns
  • Assemble layout with Grid and Flexbox
  • Add responsiveness with breakpoints
  • Iterate and fix issues

For example, this card component:

Requires utility classes like:

p-4 md:p-6
bg-white
drop-shadow-md 
rounded-lg
max-w-xs

Build it into a reusable component:

<!-- Card.js -->
<div class="p-4 md:p-6 bg-white drop-shadow-md rounded-lg max-w-xs">

  <!-- Component implementation -->

</div>

This declarative process accelerates development directly from designs.

Day 4 - Tailwind Plugins

One of Tailwind's biggest strengths is its plugin ecosystem. Plugins extend Tailwind's functionality without bloating the core framework.

Plugins fall into categories like:

  • Components - New abstractions like modal and dropdown
  • Styles - Extra utilities like border and box-shadow
  • Animations - Libraries like Animate.css
  • Tools - IDE extensions, optimizations, etc

When choosing plugins, opt for popular ones with strong documentation and ongoing support. Learn the source code to understand how they work.

You register plugins in tailwind.config.js:

module.exports = {
  plugins: [
    require('tailwindcss-border-gradients'),
    plugin(({ addUtilities }) => {
      addUtilities({
        '.bg-gradient-rainbow': {
          'background-image': 'linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet)' 
        }
      })
    })
  ]
}

Plugins should thoughtfully extend your toolkit without bloat. Let's see some useful examples.

Animation Plugins

For transition effects, animate.css is a popular plugin:

<div
  class="animate-fade-in" 
  animate-duration="0.3s"
  animate-delay="0.2s"> 
</div>

It adds fade, slide, zoom, bounce, and other animations.

Use sequences for microinteractions:

<button
  onClick="open = !open"
  class="duration-500" 
>
  Toggle
</button>

<div
  x-show="open"
  x-transition.scale.80
  class="hidden duration-700">
   
  <p>Content</p>
  
</div>

This scales the div in when toggled open.

Component Plugins

Plugins like Headless UI add new abstractions:

<Transition>
  <div>
    <!-- Transition content -->
  </div>
</Transition>

This handles enter/leave animations, making transitions reusable across your app.

Other popular plugins include:

  • @tailwindcss/forms - Styled form components
  • @tailwindcss/typography - Prose styles
  • @tailwindcss/aspect-ratio - Aspect ratio boxes

Choose plugins carefully to avoid bloating your project.

Day 5 - Advanced Customization

Once you grasp Tailwind's fundamentals, the next step is advanced customization for greater control.

Techniques like theme configuration, plugins, variants, and @apply give you nearly unlimited flexibility without sacrificing maintainability. Let's go deeper.

Theme Configuration

Tailwind's theme config allows custom colors, fonts, sizes, shadows, breakpoints, and much more:

// tailwind.config.js
module.exports = {
  theme: { 
    extend: {
      colors: {
        'brand': '#FF6363' 
      }
    }
  }
}

This generates the .bg-brand-500 utilities automatically.

The defaultTheme file shows everything you can customize.

Use this to match your design system, branding, spacing, and typography perfectly.

Plugins

We've covered plugins already, but combining them unlocks new possibilities: