Create a modern responsive website: Master the Tailwind CSS framework from scratch

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

In the field of modern front-end development, CSS frameworks that follow the “Utility-First” principle are becoming the mainstream choice for building efficient and maintainable user interfaces. Among them,Tailwind CSS It stands out for its high flexibility and development efficiency. It is different from traditional component libraries (such as…) BootstrapIt does not provide pre-made button or card components; instead, it offers a set of finely-grained utility classes that allow developers to build any desired design by directly combining these classes within HTML.

The core philosophy of this approach is to move style decisions back from the CSS files into the markup language itself, thereby eliminating the cognitive burden of constantly switching back and forth between the style sheet and the HTML code. By using techniques such as… flexpt-4text-center and rotate-90 With such a class, you can create intuitive user interfaces while keeping the size of your CSS files extremely small.

Why choose Tailwind CSS?

Among the many CSS frameworks available,Tailwind CSS Its unique advantages make it the preferred choice for many developers and teams.

Recommended Reading Unlock Tailwind CSS: A Practical Guide to Front-End Development, from Beginner to Expert

Ultimate development efficiency and flexibility

Traditional CSS writing requires naming classes for each element and defining rules in a separate style sheet. This process often leads to an overuse of class names and style conflicts. Tailwind CSS By providing a complete set of detailed, granular tool classes, you can directly apply styles in HTML. For example, to create a button with padding, a blue background, and white text, you simply need to write:

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
<button class="px-4 py-2 bg-blue-600 text-white rounded-lg">
  点击我
</button>

This approach greatly speeds up the prototyping and development iteration process, as you don’t need to switch between different files, nor do you have to worry about how to name a style that is only used for this specific purpose.

A highly customizable design system

Tailwind CSS Everything is configurable. This can be done through the files located in the project’s root directory. tailwind.config.js With the configuration file, you have complete control over the design system of your project. You can define your own color palettes, spacing ratios, breakpoints, font sizes, and more. For example, you can easily change the default blue theme color to your brand’s color.

// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      colors: {
        'brand-blue': '#1a73e8',
      }
    }
  }
}

After the configuration is completed, you can use it in your project. bg-brand-blue Such a class. This design enables… Tailwind CSS It can seamlessly integrate with any existing design guidelines, rather than forcing you to adopt the aesthetic style of the framework.

Build-time optimization and an extremely small production footprint

Tailwind CSS utilization PurgeCSS(In newer versions, this feature is called “Content Scanning”) It is used to optimize the production build process. The system scans your project’s files (such as HTML, JavaScript, Vue, React components) to identify all the tool classes that are being used, and then removes any unused CSS code. As a result, the final CSS file only contains the styles that you have actually applied to your code. This typically results in a CSS file size of less than 10KB, which significantly improves performance.

Recommended Reading Explore Tailwind CSS: A Practical Technical Guide from Beginner to Expert

How to start using Tailwind CSS

I'm going to visit my grandmother this weekend. Tailwind CSS Integrating it into your project is very simple; there are mainly two ways to do it: you can get a quick start using a CDN, or you can proceed with professional development using build tools.

Quick experience through CDN

For learning, prototyping, or simple demonstrations, you can directly include the content using a CDN (Content Delivery Network) link. Simply add the relevant code to your HTML file. <head> Add the following code inside the tag:

<script src="https://cdn.tailwindcss.com"></script>

This is the fastest way to get started, but please note that you won’t be able to use this method. Tailwind CSS Some of its advanced features include custom configurations and commands.@apply@variants) as well as the most important optimization for production environments (Purge). Therefore, it is not recommended for use in official production projects.

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

Professional installation using PostCSS

For production-level projects, it is recommended to use the PostCSS installation method, as this will unlock additional features and improvements. Tailwind CSS Use all of your capabilities. First, initialize the project using npm or yarn and install the dependencies:

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

Next, create. postcss.config.js The file, and configure it to use… Tailwind CSS and Autoprefixer

// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

Then, in your main CSS file (for example… src/styles.cssIn this article, we introduce Tailwind CSS The instruction:

Recommended Reading Mastering the core concepts of Tailwind CSS: From practical classes to responsive design in action

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

Finally, make sure that your… tailwind.config.js The file has its content path configured, so that the tool can scan and optimize it correctly.

// tailwind.config.js
module.exports = {
  content: ["./src/**/*.{html,js}"],
  theme: {
    extend: {},
  },
  plugins: [],
}

Now, you can freely use all the utility classes in the project’s HTML or components. This can be done by running the build command (for example…). npm run build),Tailwind CSS An optimized style file will be generated.

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!

Core Utility Classes and Responsive Design

Tailwind CSS The utility class library covers almost all common CSS properties and includes a powerful responsive design system.

A quick overview of commonly used tools

The utility classes follow a unified naming convention, which makes them easy to remember. For example:
Layout:flex, grid, block, hidden
Spacing:p-4(Padding)m-2(Margin)mt-8(Top margin)
Size:w-full(Width: 100%)h-screen(The height is equal to the height of the viewport.)
Color:bg-gray-100(Background color),text-red-500(Text color)
Typography:text-xl(Font size)font-bold(Weight of the text)text-center(Text alignment)

Implement a responsive layout

Responsive design is Tailwind CSS Its strength lies in its mobile-first breakpoint system. The default styles are designed for mobile devices, and additional styles are applied to larger screens using specific prefixes. The available breakpoint prefixes include:
- sm: (640px)
- md: (768px)
- lg: (1024px)
- xl: (1280px)
- 2xl: (1536px)

For example, to create a layout with two columns that stack on mobile devices and appear side by side on medium-sized screens:

<div class="flex flex-col md:flex-row">
  <div class="w-full md:w-1/2 p-4 bg-blue-100">Left sidebar</div>
  <div class="w-full md:w-1/2 p-4 bg-green-100">Right-side column</div>
</div>

You can also easily control the visibility of elements – whether to show them or hide them.hidden md:block This indicates that the content will be displayed on screens with a medium size or larger, and will be hidden on mobile devices.

Hover and focus states

Tailwind CSS It also includes various state variants, which allows you to easily style interactive elements. You simply need to add a state prefix before the class name in your utility classes. hover:focus:active:

<button class="bg-blue-500 hover:bg-blue-700 focus:ring-2 focus:ring-blue-300 ...">
  交互按钮
</button>

You can even do this in the configuration file by… variants The options allow you to customize which tool classes support which states.

Advanced Features and Customization

Once you become familiar with the basic usage,Tailwind CSS The advanced features provided can help you write more concise and maintainable code.

Extract components and reuse styles

Although it's convenient to use utility classes directly in HTML, if the same complex set of styles needs to be applied in multiple places, re-writing the code would be redundant. In such cases, you can use… @apply The instruction extracts component classes from the CSS code.

/* 在你的CSS文件中,例如 styles.css */
.btn-primary {
  @apply px-4 py-2 bg-blue-600 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 directly use this custom class in HTML:<button class=“btn-primary”>This approach not only retains the convenience of using tools but also avoids code duplication.

Use the plug-in to extend its functionality

Tailwind CSS It boasts a rich plugin ecosystem. You can install either official or community-made plugins to add new functionality or tools to your application. For example,@tailwindcss/forms The plugin provides better default styles for form elements.@tailwindcss/typography The plugin can quickly improve the appearance of unpredictable HTML content from CMS systems (such as blog posts). After installation, you simply need to… tailwind.config.js The plugins Just introduce it into the array.

Deeply customized configuration

Almost all design tokens can be used. tailwind.config.js Customize it as needed. You can expand its functionality.extendThe default theme can be used, or it can be completely overridden.themeFor example, you can customize rounded corners, shadows, and even add new variants of tool classes.

module.exports = {
  theme: {
    extend: {
      animation: {
        'spin-slow': 'spin 3s linear infinite',
      }
    }
  },
  variants: {
    extend: {
      backgroundColor: ['active'], // 为背景色工具类启用 active 状态
    }
  }
}

summarize

Tailwind CSS By adopting a prioritization-based approach, it has completely transformed the way developers write CSS. It brings style decisions back to the markup level and enables unparalleled development speed and design flexibility through the combination of finely crafted utility classes. Its highly customizable design system allows it to perfectly fit any brand or design guidelines, while build-time optimizations ensure the ultimate performance of the final product. Whether it’s for creating quick prototypes or complex enterprise-level applications…Tailwind CSS All of them offer a powerful, efficient, and maintainable set of styling solutions. Mastering them means that you have acquired the core productivity tools for building modern, responsive web interfaces.

FAQ Frequently Asked Questions

What are the differences between Tailwind CSS and Bootstrap?

Tailwind CSS It is a CSS framework that prioritizes functionality over aesthetics (Utility-First). It does not provide pre-made components with specific styles, such as navigation bars or cards. Instead, it offers low-level utility classes that you can use to build completely custom components on your own by combining them.

Bootstrap It is a traditional component library that offers a range of pre-designed components with fixed styles. Although it also provides some utility classes, its main focus is on pre-made components. Bootstrap It's possible to quickly create interfaces with a consistent style, but for in-depth customization, it's often necessary to override a large number of default styles. Tailwind CSS Full customization is encouraged and implemented from the very basics.

Will writing a large number of class names directly in HTML make the code more confusing?

This is a common concern at the initial stage. In fact, it’s much easier to understand and work with when the style descriptions are presented in a clear and intuitive manner within the HTML code, rather than having to write numerous rules for custom class names in the CSS file. flex items-center justify-betweenIt is often clearer and easier to maintain. It eliminates the need to jump between files and deal with the hassle of naming them.

For complex and repetitive style combinations, you can use… @apply Use directives or component-based frameworks (such as React or Vue components) to encapsulate the functionality, in order to keep the HTML code clean and tidy. The team can also ensure consistency by establishing conventions for the naming of classes and their combinations.

How to add custom colors or sizes to Tailwind CSS?

All customizations are located in the root directory of the project. tailwind.config.js The file has been completed. You can… theme.extend Add new configuration items under the object to extend the default theme.

For example, to add a custom color, you can write it like this:

module.exports = {
  theme: {
    extend: {
      colors: {
        'custom-gray': '#f5f5f5',
      },
      spacing: {
        '128': '32rem',
      }
    }
  }
}

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

Will Tailwind CSS affect website performance?

On the contrary,Tailwind CSS After proper configuration, performance is usually significantly improved. The production build process utilizes PurgeCSS technology, which scans all your template files and only includes the CSS classes that are actually used in the final style sheet. As a result, the generated CSS file is very small (often less than 10KB), which reduces the load on the network and speeds up page loading times.

Does it support dark mode?

Yes.Tailwind CSS Out-of-the-box support for dark mode is available. You can… tailwind.config.js Passed in the middle darkMode: ‘class’ Or darkMode: ‘media’ To enable it, follow these steps. Once enabled, you will be able to use it. dark: Use a variant prefix to apply the dark mode styles.

For example.dark:bg-gray-800 This indicates that a dark gray background will be applied in dark mode. If set to... ‘class’ In the case of the model, you need to place it within the root element of the HTML (such as ). <html>) Add or remove them manually class=“dark” To switch modes; if set to... ‘media’It will automatically switch according to the color preferences of the user's operating system.