A comprehensive guide to using Tailwind CSS for building modern, responsive web pages

2-minute read
2026-03-18
2,119
I earn commissions when you shop through the links below, at no additional cost to you.

In the field of web front-end development, where efficiency is highly valued today,Tailwind CSS It has rapidly gained popularity thanks to its unique philosophy of “Utility-First” (putting functionality first). Unlike traditional CSS frameworks that provide pre-packaged components such as buttons and cards, it offers a set of finely-grained, atomic CSS class names. Developers can use these class names to directly build custom user interfaces in HTML, allowing for quick and flexible customization.

What is Tailwind CSS?

Tailwind CSS Essentially, it is a CSS framework designed for quickly building modern user interfaces. It works by providing a large number of composable, single-purpose utility classes, with each class typically corresponding to just one CSS property. For example,p-4 in the name of padding: 1rem;text-center in the name of text-align: center;

\nCore design philosophy

Tailwind CSS The core principle of this approach is “practicality first.” This means that it encourages developers to combine detailed style classes directly within HTML tags, rather than writing custom, semantic class names in a separate CSS file. The advantage of this method is that you don’t have to worry about how to name the classes, nor do you need to constantly switch back and forth between the HTML and CSS files.

Recommended Reading Master the core concepts of Tailwind CSS in one article: from beginners' guide to practical layout guidance

It utilizes a highly configurable system. tailwind.config.js The file allows developers to have full control over the design system, including all design elements such as colors, spacing, fonts, and breakpoints (also known as “Design Tokens”). This approach ensures that the resulting CSS file is optimized during the build process using tools like PurgeCSS (or the built-in Purge feature of Tailwind CSS). As a result, the CSS file only contains the classes that are actually used in the project, which helps to minimize the size of the final output.

WordPress.com Website Builder Assistant
WordPress.com Website Builder Assistant
99.999% Availability + Cross-zone Disaster Recovery, 24/7 Support, Free AI Build Site with Blog Package Purchase
Free domain name for one year
Visit WordPress.com Website Builder Helper →
UltaHost Website Builder Assistant
UltaHost Website Builder Assistant
900+ Free, Customizable Templates to Get the SEO Power You Need to Optimize Your Site for Search Exposure

The main differences from frameworks like Bootstrap:

Traditional frameworks such as… Bootstrap The components provided are pre-made and have a specific appearance. Although they allow for fast development, customization often requires overriding the framework’s own styles, which can lead to conflicts in CSS specificity and result in bloated code.Tailwind CSS It does not provide any components with a default appearance; it only offers the “raw materials” needed to build components. This gives your website a high degree of uniqueness, preventing it from having the uniform, “Bootstrap-like” look that is commonly seen. At the same time, it maintains extremely high development efficiency.

How to start using Tailwind CSS

start usingTailwind CSSThere are several ways to do this, and the most recommended ones are using its official CLI tool or integrating it with front-end build tools. Here are the installation steps using Node.js and PostCSS:

Install and configure using npm.

First, initialize the npm project in the project root directory (if it hasn't been initialized yet), and then install Tailwind CSS and its dependencies.

npm init -y
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init

This command will generate a default one. tailwind.config.js Configuration file. Next, you need to configure the content scanning path for this file to ensure that unused styles are correctly removed during the production build process.

Recommended Reading In-depth Analysis of Tailwind CSS: How to Build Modern, Responsive Interfaces Using a Practical Prioritization Framework

// tailwind.config.js
module.exports = {
  content: ["./src/**/*.{html,js}"], // 根据你的项目结构调整路径
  theme: {
    extend: {},
  },
  plugins: [],
}

Create and introduce basic styles.

In your main CSS file (for example, src/input.cssIn this section, we introduce the core commands of Tailwind CSS.

/* src/input.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

Then, compile this CSS file using build tools such as Vite or Webpack, or by employing the Tailwind CLI. For example, you can use the following CLI command:

npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch

Finally, link to the compiled output in your HTML file. output.css The document.

Bluehost Website Builder
Offers AI website creation tool, 24/7 live chat & phone support, free domain name for 1 year, free CDN, 99.99% uptime SLA
<!doctype html>
<html>
<head>
  <link href="/dist/output.css" rel="stylesheet">
</head>
<body>
  <h1 class="text-3xl font-bold text-blue-600">Hello, Tailwind!</h1>
</body>
</html>

Detailed Explanation of Core Features and Utility Classes

Tailwind CSS The utility classes cover the vast majority of CSS properties and adhere to a consistent set of design rules.

Layout and spacing system

Layout classes such as flex, grid, block, inline-block These correspond directly to CSS. display Properties. The spacing system is one of its key features; it uses a consistent scaling factor (by default, multiples of 4px, meaning 1 unit = 0.25rem). For example:
- m-4: margin: 1rem;
- p-2: padding: 0.5rem;
- mt-8: margin-top: 2rem;
- px-4: padding-left: 1rem; padding-right: 1rem;

Color and Formatting Controls

The color system is… tailwind.config.js The theme.colors It is defined within the document, and a wealth of default values are provided. You can simply use it as is. text-blue-500, bg-gray-100, border-red-300 Such a class.

Recommended Reading The Essence of Tailwind CSS: Unveiling the Working Principles of this Practical, Atomic CSS Framework

The typesetting capabilities are equally powerful:
- text-xs to text-9xl Control the font size.
- font-normal, font-medium, font-bold Control the weight of the characters in the text.
- text-center, text-left Control the alignment.

Responsive design and state variants

Responsive design is implemented through prefixes added to class names. Tailwind uses a mobile-first breakpoint system, with default breakpoints predefined in the framework. sm, md, lg, xl, 2xlTo add responsive behavior to a certain style, simply add the breakpoint prefix before it.

hosting.com
Free SSL, Cloudflare CDN, WAF, 40+ global server rooms to choose from, lower latency near you, 24/7/365 service support, you can now save up to 67%, support for AI builds and SEO optimization!
<!-- 默认移动端样式,中等屏幕及以上应用新样式 -->
<div class="text-base md:text-lg lg:text-xl">Responsive text</div>

Status variants allow you to apply styles to different interaction states. You simply need to add the appropriate prefix before the class name. For example:
- hover:bg-blue-700 (Mouse hover)
- focus:ring-2 (Focused)
- active:scale-95 (Activate by clicking)
- dark:bg-gray-800 (Dark mode)

Advanced techniques and best practices

Once you have mastered the basics, some advanced techniques can help you make the most of Tailwind’s capabilities.

Extracting components and using the @apply directive

Although the principle of “practicality first” is advocated, when a certain UI pattern (such as a button with a specific design) appears repeatedly in a project, it is still advisable to use it consistently. @apply It’s a good habit to extract these elements into separate CSS components using appropriate instructions. You can do this in your custom CSS files.

/* 在 input.css 中,在 @tailwind components; 之后添加 */
.btn-primary {
  @apply py-2 px-4 bg-blue-500 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75;
}

Then you can use it in HTML. class=”btn-primary”Please note that overuse can lead to negative consequences. @apply It will likely lead back to the practice of writing custom CSS, so it should be used with caution.

\nDeeply customized design system

All default values are available. tailwind.config.js The document's theme Some parts can be overridden or extended. For example, you can add custom colors or adjust the spacing ratio.

// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      colors: {
        'brand-blue': '#1992d4',
      },
      spacing: {
        '128': '32rem',
      }
    },
  },
}

After that, you can use it. bg-brand-blue and w-128 Such a class.

Combined with JavaScript frameworks

Tailwind CSS It integrates seamlessly with modern JavaScript frameworks such as React, Vue, and Svelte. In React, you can directly use class name strings, or you can use tools like… clsx Or classnames Such libraries are used to conditionally combine class names.

// React 组件示例
function Button({ children, isPrimary }) {
  const className = clsx(
    'py-2 px-4 rounded-lg font-semibold',
    isPrimary 
      ? 'bg-blue-500 text-white hover:bg-blue-700'
      : 'bg-gray-200 text-gray-800 hover:bg-gray-300'
  );
  return <button className={className}>{children}</button>;
}

summarize

Tailwind CSS It has truly revolutionized the way developers write CSS by adopting a prioritized approach. By providing a set of atomic, composable class names, it has elevated the efficiency of style construction to a new level, while ensuring that the final product is highly customizable and optimized in terms of performance. Although it requires memorizing a large number of class names at the beginning of the learning process, once you become familiar with the naming logic, your development speed will experience a significant improvement. It is especially suitable for modern web projects that require unique designs, high development efficiency, and strict constraints on the final file size.

FAQ Frequently Asked Questions

Will the CSS files generated by Tailwind CSS be very large?

No. In formal production environment setups, Tailwind is tightly integrated with PurgeCSS (or similar tools). It scans your project’s files (such as HTML, JSX, and Vue templates) to identify all the Tailwind class names that are being used, and then only includes these styles in the final CSS file. Unused styles are completely removed, resulting in a much smaller final CSS file.

Will writing so many class names in HTML make the code difficult to read and maintain?

This is a common concern. Practice has shown that writing styles directly on HTML elements actually closely couples the related styles with the structure, making it unnecessary to switch between multiple files when reading the code. For long lists of class names, readability can be maintained by using proper line breaks and grouping (for example, grouping classes related to layout, dimensions, colors, etc.). It is also very helpful to establish consistent conventions for naming classes within the team.

How to override the Tailwind CSS styles of third-party components?

Because the utility classes in Tailwind have the same CSS weight (specificity), styles defined later will usually override those defined earlier. You can overcome this by providing more specific class names, or by using other methods to manage the order of style application. !important Variants (such as bg-red-500 !important Instead of writing it directly in the class name, it is added through an additional process. ! You can use prefixes (but use them with caution) to override the default behavior. A better approach is to pass in a custom class name directly through the configuration, if the third-party component allows it.

Does Tailwind CSS support dark mode?

Full support is available. Tailwind CSS includes built-in variants for the dark mode theme. You need to… tailwind.config.js Settings in... darkMode: ‘class’ Or darkMode: ‘media’Set to ‘class’ When this happens, you need to manually add the attribute to the root element of the HTML (such as ). Add or remove items on the list class=”dark” Let’s switch the mode; set it to… ‘media’ It will automatically switch according to the dark mode settings of the user's operating system. Then you can use it. dark: Use prefixes to define the styles in dark mode, for example: dark:bg-gray-900