Tailwind CSS practical tips and best practices
Share tips on using Tailwind CSS in real projects, including custom design systems, performance optimization, and solutions to common problems.
Custom design token
Define project-specific design tokens in tailwind.config.mjs:
theme: {
extend: {
colors: {
primary: { /* 色阶 */ },
surface: { /* 色阶 */ },
},
},
},
Commonly used techniques
1. Use @apply to extract public styles
@layer components {
.btn-primary {
@apply px-4 py-2 bg-primary-500 text-white rounded-lg
hover:bg-primary-600 transition-colors duration-200;
}
}
2. Responsive design
Tailwind’s breakpoints are mobile-first:
sm:640pxmd:768pxlg:1024pxxl:1280px
3. Dark mode
Use the dark: prefix to easily implement dark mode:
<div class="bg-white dark:bg-gray-900">
<p class="text-gray-900 dark:text-white">自适应内容</p>
</div>
Performance optimization
- Ensure
contentis configured correctly to avoid generating unused CSS - Generate styles on demand using JIT mode
- Automatic tree-shake during build
Summarize
Tailwind CSS 让样式开发更高效,通过合理使用自定义配置和工具类,可以快速构建出一致且美观的界面。