Tailwind CSS: Thực hành Tốt nhất
Xuất bản ngày
bởi Nguyễn Công Dũngtailwindcssresponsivetutorial
Tailwind CSS: Thực hành Tốt nhất
Tailwind CSS là một framework CSS utility-first cho phép bạn xây dựng thiết kế hiện đại nhanh chóng. Dưới đây là một số thực hành tốt nhất để giữ code Tailwind của bạn dễ bảo trì và hiệu quả.
Trích xuất Component
Đừng lặp lại các chuỗi class dài. Trích xuất chúng thành components:
// ❌ Không tốt
<button className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
Nhấn tôi
</button>
// ✅ Tốt
function Button({ children, ...props }) {
return (
<button
className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
{...props}
>
{children}
</button>
);
}Sử dụng @apply cho Patterns Lặp lại
Đối với các pattern thực sự lặp lại, sử dụng @apply:
.btn-primary {
@apply px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors;
}Responsive Design
Sử dụng các prefix responsive một cách nhất quán:
<div className="
text-sm md:text-base lg:text-lg
p-4 md:p-6 lg:p-8
">
Nội dung
</div>Dark Mode
Tận dụng các utility dark mode:
<div className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
Nội dung
</div>Cấu hình Tùy chỉnh
Mở rộng Tailwind config cho các giá trị cụ thể của dự án:
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
brand: {
50: '#f0f9ff',
500: '#0ea5e9',
900: '#0c4a6e',
},
},
},
},
};Mẹo Hiệu suất
- Purge unused styles: Đảm bảo các đường dẫn
contentchính xác - Tránh arbitrary values: Sử dụng theme values khi có thể
- Nhóm các utility liên quan: Giữ các class liên quan cùng nhau
- Sử dụng JIT mode: Bật Just-In-Time compilation để build nhanh hơn
Patterns Phổ biến
Component Card
<div className="bg-white rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow">
{content}
</div>Container
<div className="container mx-auto px-4 max-w-7xl">
{content}
</div>Flexbox Centering
<div className="flex items-center justify-center min-h-screen">
{content}
</div>Chúc bạn styling vui vẻ!