Starting from scratch: Use Tailwind CSS to quickly build a modern responsive webpage

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

In the past few years, the field of front-end development has witnessed the rise of CSS frameworks that prioritize practicality (Utility-First). Tailwind CSS It is undoubtedly one of the best in its class. By offering a range of finely-grained, composable, and practical classes, it has completely transformed the way developers build user interfaces. Unlike traditional CSS frameworks (such as Bootstrap),Tailwind CSS No pre-made components are provided; instead, the original tools for building these components are offered. This shift in paradigm results in faster development speeds, greater customization options, and the ability to easily create fully responsive designs.

This article will guide you from scratch in learning how to use… Tailwind CSS The powerful features of this tool allow us to efficiently create responsive web pages that meet modern standards. We will cover the entire process, from setting up the development environment to the actual deployment of the website.

The core concepts and advantages of Tailwind CSS

Before delving into in-depth study, it is important to understand... Tailwind CSS The design philosophy of this project is of utmost importance. Its core principle is “Utility-First,” which means that the styling is achieved by directly applying numerous small, single-purpose classes within the HTML code.

Recommended Reading Master Tailwind CSS: From Atomic Tools to Practical Guidelines for Efficient Responsive Web Development

The “Practicality First” paradigm

The traditional way of writing CSS requires you to create semantic class names for each component (for example… .btn-primaryThen, define the styles for these classes in a separate CSS file. Tailwind CSS Then I encourage you to use something like that directly. bg-blue-500 text-white font-bold py-2 px-4 rounded Such class combinations are used to create buttons. This approach eliminates the overhead of constantly switching between HTML and CSS files; all the styles are clearly displayed within the markup.

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

High degree of customizability

Tailwind CSS All the styles for this element are defined through a single file or set of rules that is named… tailwind.config.js The configuration file is used to drive the application’s appearance and behavior. In this file, you can easily define the project’s design system: including color palettes, fonts, spacing ratios, breakpoints (for responsive design), and more. This means that you can customize the styles exactly according to the design specifications, without being limited by the framework’s default themes.

Built-in support for responsive design

Responsive design is Tailwind CSS Its strength lies in its mobile-first breakpoint system, which comes with five default breakpoint prefixes:sm:, md:, lg:, xl:, 2xl:You just need to add these prefixes before the class names, and you can easily specify the styles for different screen sizes.

<!-- 默认在移动端显示为块级元素,在中等屏幕及以上尺寸显示为行内块元素 -->
<div class="block md:inline-block">Responsive elements</div>

Project Initialization and Environment Configuration

start using Tailwind CSS There are various ways to do this, including using a CDN, CLI tools, or integrating with front-end build tools. For the best experience (such as JIT mode, Tree Shaking, etc.), we recommend using its command-line tools or integrating with PostCSS.

Quickly get started using the Tailwind CLI.

This is the fastest way to get started. First, make sure that Node.js is installed on your system. Then, execute the following commands in the project directory:

Recommended Reading Starting from scratch: Building a modern responsive web interface using Tailwind CSS

# 初始化 package.json 文件(如果不存在)
npm init -y

# 安装 Tailwind CSS
npm install -D tailwindcss

# 生成 tailwind.config.js 配置文件
npx tailwindcss init

Next, create a CSS entry file, for example… src/input.cssAnd add Tailwind CSS The instruction:

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

Then, run the CLI command to build your CSS:

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

This command will listen for incoming requests. src/input.css Monitor changes to the files, and output the compiled CSS in real-time. dist/output.cssFinally, incorporate it into your HTML file. ./dist/output.css That's all.

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

Integration with build tools (taking Vite as an example)

If you use modern front-end build tools like Vite, the integration process is much smoother. After creating a Vite project, you simply need to install and configure it. Tailwind CSS

# 创建 Vite 项目
npm create vite@latest my-project -- --template vanilla
cd my-project

# 安装 Tailwind CSS 及其依赖
npm install -D tailwindcss postcss autoprefixer

# 初始化配置文件
npx tailwindcss init -p

This will generate… tailwind.config.js and postcss.config.js Two files. Then, make the modifications. tailwind.config.js File, configuration content path:

/** @type {import('tailwindcss').Config} */
export default {
  content: ["./*.html", "./src/**/*.{js,ts}"], // 根据你的项目结构调整
  theme: {
    extend: {},
  },
  plugins: [],
}

Then, in your main CSS file (for example, src/style.css) is introduced into Tailwind CSS The instruction has been given. Now, proceed with the execution. npm run devThen you can use it in the project. Tailwind CSS Okay.

Recommended Reading The Ultimate Guide to Tailwind CSS: From Beginner to Expert, Building Modern Websites

Building responsive components using Tailwind CSS

After mastering the environment configuration, let’s get to work on building some common responsive components to gain a direct understanding of their working processes.

Build a navigation bar.

A responsive navigation bar typically displays horizontally on desktop devices and folds into a hamburger menu on mobile devices. Tailwind CSS It can be easily achieved.

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!
<nav class="bg-gray-800 p-4">
  <div class="container mx-auto flex flex-wrap items-center justify-between">
    <!-- 品牌Logo -->
    <a href="#" class="text-white text-xl font-bold">My brand</a>

<!-- 汉堡菜单按钮(移动端显示) -->
    <button class="md:hidden text-white focus:outline-none" id="menu-button">
      <svg class="w-6 h-6" fill="none" stroke="currentColor" viewbox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"/>
      </svg>
    </button>

<!-- 导航链接 -->
    <div class="hidden w-full md:flex md:w-auto md:items-center" id="menu">
      <ul class="flex flex-col mt-4 md:flex-row md:space-x-8 md:mt-0">
        <li><a href="#" class="block py-2 text-gray-300 hover:text-white">Home</a></li>
        <li><a href="#" class="block py-2 text-gray-300 hover:text-white">Regarding</a></li>
        <li><a href="#" class="block py-2 text-gray-300 hover:text-white">Service</a></li>
        <li><a href="#" class="block py-2 text-gray-300 hover:text-white">Contact</a></li>
      </ul>
    </div>
  </div>
</nav>

<script>
  // 简单的 JavaScript 用于切换移动端菜单
  document.getElementById('menu-button').addEventListener('click', function() {
    const menu = document.getElementById('menu');
    menu.classList.toggle('hidden');
  });
</script>

In this example,md:hidden and md:flex Class-based controls determine whether elements are displayed or hidden at different breakpoints.flex-col and md:flex-row The layout direction has been controlled.

Build a card component

Cards are a common component used to display content on web pages. Here is an example of a card with a hover effect and a responsive image:

<div class="max-w-sm rounded overflow-hidden shadow-lg bg-white mx-auto my-8">
  <!-- 响应式图片容器 -->
  <div class="w-full h-48 md:h-64 overflow-hidden">
    <img class="w-full h-full object-cover hover:scale-105 transition-transform duration-300"
         src="https://picsum.photos/400/300"
         alt="Card image">
  </div>
  <div class="px-6 py-4">
    <div class="font-bold text-xl mb-2 text-gray-800">Card title</div>
    <p class="text-gray-700 text-base">
      This is a descriptive text about a card. On both mobile and desktop devices, its layout and font size can adapt automatically.
    </p>
  </div>
  <div class="px-6 pt-4 pb-6">
    <span class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2"># Tag 1</span>
    <span class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2"># Tag 2</span>
  </div>
</div>

The following elements/technologies were used here: h-48 md:h-64 Let the image height change according to different screen sizes.hover:scale-105 and transition-transform A smooth hover-to-zoom effect has been implemented.

Advanced Techniques and Production Optimization

As projects grow larger, mastering some advanced techniques and optimization strategies can help you use your resources more efficiently. Tailwind CSS

Use @apply to extract duplicate classes.

Although the principle of “practicality first” is a core concept, when a certain class is used multiple times within a project (for example, a button with a specific design), it is acceptable to… @apply The instruction extracts the relevant content and assigns it to a custom CSS class, in order to maintain the simplicity of the HTML code.

In your CSS file (for example, input.cssAdd the following to:

.btn-primary {
  @apply bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg shadow-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75 transition duration-150 ease-in-out;
}

Then, you can directly use it in HTML. class="btn-primary" That's all.

Deep customization of configuration files

Open it tailwind.config.jsYou can make comprehensive customizations. For example, you can expand the range of available theme colors:

module.exports = {
  theme: {
    extend: {
      colors: {
        'brand-blue': '#1992d4',
        'brand-green': '#0ca678',
      },
      spacing: {
        '128': '32rem',
      }
    },
  },
  plugins: [],
}

Once it's defined, you can then use it just like… bg-brand-blue and w-128 Here’s such a new class.

Enabling JIT mode and production builds

Starting from version 3.0,Tailwind CSS The Just-In-Time (JIT) compiler is enabled by default. It generates styles on demand as you write your templates, which significantly speeds up the development process and reduces the size of the final CSS file. For the production environment, make sure to set this option in your build commands. NODE_ENV=productionTailwind CSS Tree Shaking will be performed automatically to remove all unused styles.

Configure scripts in package.json:

{
  "scripts": {
    "dev": "tailwindcss -i ./src/input.css -o ./dist/output.css --watch",
    "build": "NODE_ENV=production tailwindcss -i ./src/input.css -o ./dist/output.css --minify"
  }
}

Run npm run build You will receive a CSS file that has been compressed and optimized.

summarize

Tailwind CSS By employing a prioritized methodology, it provides front-end developers with an efficient, flexible, and highly maintainable solution for styling. It eliminates the traditional need to switch back and forth between different files, integrating style decisions directly into the HTML coding process, thereby accelerating the development process. Its powerful responsive features and deeply customizable configuration system enable it to handle everything from simple personal websites to complex enterprise-level applications with ease.

Although you need to memorize some class names in the initial stage, the improvement in development efficiency is significant once you get familiar with them. Combined with its JIT (Just-In-Time) engine and excellent optimization capabilities for production code,Tailwind CSS Undoubtedly, it is a powerful tool for building modern, responsive web pages.

FAQ Frequently Asked Questions

Will Tailwind CSS make HTML look bloated?

This is indeed a common concern. Seeing a large number of class names in HTML can initially seem confusing and messy. However, this “bloat” actually leads to extreme flexibility and faster development. You no longer have to spend hours coming up with creative class names, nor do you need to maintain a huge CSS file that might contain a lot of unnecessary styles. Additionally, you can use… @apply The instructions recommend extracting commonly used utility classes into component classes to maintain the cleanliness and organization of the templates.

How to override or modify the default styles of Tailwind CSS?

Tailwind CSS The design itself encourages customization and adaptation. The main way to achieve this is by making modifications. tailwind.config.js Configuration file. You can… theme.extend You can add new values to expand the default theme, or you can also... theme The existing key-value pairs are directly overwritten to replace the default values. For one-time style overrides, you can use the bracket notation to generate any desired value. For example: top-[117px] Or bg-[#1da1f2]

Which front-end frameworks is Tailwind CSS suitable for using with?

Tailwind CSS It integrates perfectly with almost all major front-end frameworks and libraries. Whether it’s component-based frameworks like React, Vue, Angular, or Svelte, or meta-frameworks like Next.js, Nuxt.js, or Gatsby, the official documentation provides detailed integration guides. Its class-based design pattern complements the component-oriented approach of these frameworks, allowing you to use Tailwind’s classes directly in JSX, Vue templates, and other contexts.

In a production environment, will the final CSS file be very large in size?

No, that's exactly what I mean. Tailwind CSS One of its advantages is its ability to automatically analyze your project files (HTML, JSX, Vue components, etc.) during the build process for the production version. This is made possible by its JIT (Just-In-Time) compilation engine and the powerful PurgeCSS feature, which is built into Tailwind CSS v3+. As a result, only the CSS classes that are actually used are included in the final style sheet. This results in a very small (usually only a few KB in size) and highly optimized CSS file.