What is Tailwind CSS?
Tailwind CSS is a utility-first CSS framework that provides a set of low-level, configurable utility classes for quickly building custom user interfaces directly in HTML. Unlike frameworks such as Bootstrap or Bulma, which provide pre-designed components (e.g., buttons, cards), Tailwind provides atomized CSS classes, each of which typically corresponds to only one or a set of CSS properties. For example.text-center Corresponding to text-align: center;,.p-4 Corresponding to padding: 1rem;。
This “functional class” philosophy means that developers can “assemble” any style they want by combining these single classes without having to write custom CSS, which greatly improves the speed of development and keeps stylesheets small because eventually the This greatly improves the speed of development and keeps stylesheets small because eventually the build tool removes all unused classes through “tree-shaking optimization”.
\nCore concepts and working principles
Understanding the core concepts of Tailwind CSS is key to mastering its essence. Its design philosophy revolves around practicality, composability and responsive design.
Recommended Reading Mastering Tailwind CSS: A Practical Guide and Best Practices from Getting Started to Hitting the Ground Running。
The design philosophy that prioritizes practicality.
“Utility first” is the cornerstone of Tailwind. The framework provides a large number of fine-grained, single-function classes, such as the .bg-blue-500、.rounded-lg、.flex. Developers build complex components by combining these classes like Legos. This approach avoids the need for traditional CSS to have a semantic class name for each component (e.g. .user-card), and eliminates the context-switching costs of switching back and forth between CSS and HTML files.
Responsive design and breakpoints
Tailwind has a built-in system of responsive breakpoints with class names that can be easily prefixed to apply styles for different screen sizes. The default breakpoint prefixes include:sm:、md:、lg:、xl:、2xl:。
For example, an element stacked on mobile and aligned horizontally on a large screen can be implemented like this:
<div class="flex flex-col md:flex-row">
<div>Content 1</div>
<div>Content 2</div>
</div> This means that the default (mobile) is flex-col(vertically), on a medium screen (md:) and above becomes flex-row(Horizontal).
Configuration and Customization
Tailwind's default configuration can be found in the project's root directory via the tailwind.config.js file for deep customization. In this file, you can modify color palettes, spacing ratios, fonts, breakpoint values, and even add new utility classes.
Recommended Reading Learning Tailwind CSS: Building Modern Responsive Web Pages from Scratch。
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
'brand-blue': '#1992d4',
},
spacing: {
'128': '32rem',
}
},
},
plugins: [],
} Once customized, you can use the .bg-brand-blue and .w-128 Such a customized class.
Basic use and installation
Before you can start using Tailwind, you need to integrate it into your project; Tailwind can be installed in a number of ways, most commonly via npm or yarn.
Installation via PostCSS (recommended)
For most modern front-end projects (e.g. using Vite, Webpack), installation via PostCSS is the most integrated way to go. First, install Tailwind and its dependencies via npm:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init This will install the necessary packages and generate a default tailwind.config.js configuration file. Then, you need to create a PostCSS profile (e.g. postcss.config.js) and add Tailwind:
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
}
} Next, in your main CSS file (for example,... src/styles.cssIntroduce the Tailwind CSS directives within the code:
@tailwind base;
@tailwind components;
@tailwind utilities; Finally, make sure PostCSS is handled correctly in your project's build process. For example, in Vite or Webpack projects, they automatically read the postcss.config.js。
Recommended Reading Master Tailwind CSS: A Practical Guide and Best Practices from Beginner to Expert。
Using CDN for rapid prototype development
For quick prototypes, demos or simple HTML files, CDN links can be used. Simply add the <head> Please add the following links:
<script src="https://cdn.tailwindcss.com"></script> Note that the CDN approach does not support customization and cannot be used with the @apply directive, and because it contains all the styles, the file size is large, so it is not recommended for production environments.
Build and Production Optimization
During development, Tailwind generates a huge CSS file containing all possible classes. For production environments, a build process must be run to “shake the tree”, i.e. remove all unused classes from HTML and JavaScript components. In the tailwind.config.js In China, through content field tells Tailwind which files should be scanned for used classes:
module.exports = {
content: ['./src/**/*.{html,js,vue,jsx,tsx}'],
// ... 其他配置
} Then run the build command (e.g. npm run build), the Tailwind CLI or PostCSS plugin generates a minimized CSS file containing only the required classes.
Advanced Tips and Best Practices
Once you've mastered the basics, a few advanced tips will allow you to use Tailwind more efficiently and elegantly.
Extracting components and using the @apply directive
While combining classes directly in HTML is the main mode of Tailwind, writing a long list of classes over and over again can be redundant when a particular class combination (such as a specific style of button) is repeated multiple times in a project. In this case, you can use the @apply directive extracts reusable component classes in your CSS.
/* 在你的 CSS 文件中 */
.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, in HTML, you just need to use… class="btn-primary" That's it. Another approach that is more in line with Tailwind's philosophy is to use the componentization capabilities of JavaScript frameworks (e.g. React, Vue) to encapsulate reusable UI blocks.
Handling of hover, focus, etc.
Tailwind provides variant prefixes for various interaction states, such as hover:、focus:、active:、disabled:。
<button class="bg-blue-500 hover:bg-blue-700 focus:ring-2 focus:ring-blue-300 ...">
按钮
</button> You can also configure the tailwind.config.js The translation of the Chinese sentence into English is as follows:
\nIn the variants section to enable or disable certain state variants for specific utility classes.
Used in conjunction with JavaScript frameworks
Tailwind works well with major front-end frameworks like React, Vue, and Angular. In React, you can use JSX as usual in your className attribute using the Tailwind class. To handle dynamic splicing of class names, you can use a class like clsx Or classnames Such a tool library.
function Button({ isPrimary, children }) {
const classes = clsx(
'py-2 px-4 rounded-lg font-semibold',
isPrimary ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-800'
);
return <button className={classes}>{children}</button>;
} Extension with custom plugins
If you or your team need a specific set of utility classes that don't exist in Tailwind, you can write custom plugins. Plugins are customized by adding a custom class to the tailwind.config.js introduced in the program, you can add new utility classes, components, or base styles.
// tailwind.config.js
const plugin = require('tailwindcss/plugin');
module.exports = {
plugins: [
plugin(function({ addUtilities }) {
addUtilities({
'.scrollbar-hide': {
/* 隐藏滚动条的 CSS */
'-ms-overflow-style': 'none',
'scrollbar-width': 'none',
},
})
})
]
} summarize
Tailwind CSS revolutionizes the way developers write CSS through its utility-first approach. It shifts style decisions from style sheets to a markup language, and achieves great development efficiency and design consistency by combining a large number of fine-grained functional classes. Its powerful configuration system allows for deep customization to fit any design system, and build-time optimizations ensure that the final product is small and compact. Whether for rapid prototyping or large, complex projects, Tailwind CSS provides a powerful, flexible, and maintainable styling solution. Mastering its core concepts, workflows, and advanced techniques will give you a leg up in modern front-end development.
FAQ Frequently Asked Questions
Do Tailwind CSS styles pollute HTML?
Tailwind CSS class names do make HTML look like it contains a lot of content, but this is not “style pollution” in the traditional sense. The design is intentional; it centralizes the style logic at the view level, removes the cognitive burden of jumping between CSS and HTML, and enforces a tight coupling of style and structure, which is an advantage in component-based development.
How can I override or customize Tailwind's default classes?
There are two main ways to do this. First, you can add a new file to the tailwind.config.js The document's theme.extend section to add or extend theme values (e.g. color, spacing), which will generate new classes. Second, if you want to completely override a default value, you can add a new class to the theme part (instead of extend) to set the new value directly. For one-time overrides, adding an arbitrary value using the square bracket representation is also an option, for example top-[117px]。
What is the difference between extracting components using @apply and writing CSS directly?
utilization @apply Classes extracted by directives are still essentially a collection of Tailwind utility classes that are affected by Tailwind's configuration and are eventually processed by the build tool. Writing pure CSS directly is outside of the Tailwind ecosystem. Overuse of @apply It may take you back to writing traditional CSS, which defeats the purpose of Tailwind's “combining classes in HTML” approach. It is recommended that you only use a particular style combination with caution if it is really heavily reused. @apply。
How does Tailwind CSS perform in a production environment?
Properly built and “tree-shaking” optimized, Tailwind CSS performs very well. The build tool scans all of your source code files to find the classes that are actually used, and then generates only those classes into the final CSS file. This means that the final CSS file delivered to the user is usually much smaller than hand-written CSS or CSS using unoptimized component libraries, which improves page load speeds.
Is Tailwind suitable for use with UI component libraries?
Depending on the situation, Tailwind is a complete styling solution in its own right and usually doesn't require another complete UI component library (such as Material-UI). However, you can use component libraries built on top of Tailwind, such as Headless UI (which provides unstyled interactive components) or DaisyUI (which provides styled components). These libraries integrate seamlessly with Tailwind's themes and toolkits to further speed up development.
What's next, what's next?
Extended reading and practical knowledge
The following are related to the topic of this article and are suitable for further in-depth reading. Prioritize starting with the article that is closest to your current problem, and gradually expanding to surrounding topics usually works better.
- Web site construction: A complete technical guide to building a professional website from scratch to completion
- To build a WordPress website that is both beautiful and functional, you need to choose a theme that meets your design and functionality requirements. A good theme should:
- A Comprehensive Guide to the Entire Website Construction Process: A Step-by-Step Analysis from Zero Foundation to Professional Launch
- Mastering the Core of Tailwind CSS: A Modern Front-End Development Guide from Practical Classes to Responsive Design
- Master the entire website construction process: A technical guide and best practices from scratch to going live