Quay lại danh sách bài viết

Tailwind CSS: Thực hành Tốt nhất

Xuất bản ngày
bởi Nguyễn Công Dũng
tailwindcssresponsivetutorial

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:

React
// ❌ 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:

CSS
.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:

React
<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:

React
<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:

JavaScript
// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      colors: {
        brand: {
          50: '#f0f9ff',
          500: '#0ea5e9',
          900: '#0c4a6e',
        },
      },
    },
  },
};

Mẹo Hiệu suất

  1. Purge unused styles: Đảm bảo các đường dẫn content chính xác
  2. Tránh arbitrary values: Sử dụng theme values khi có thể
  3. Nhóm các utility liên quan: Giữ các class liên quan cùng nhau
  4. Sử dụng JIT mode: Bật Just-In-Time compilation để build nhanh hơn

Patterns Phổ biến

Component Card

React
<div className="bg-white rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow">
  {content}
</div>

Container

React
<div className="container mx-auto px-4 max-w-7xl">
  {content}
</div>

Flexbox Centering

React
<div className="flex items-center justify-center min-h-screen">
  {content}
</div>

Chúc bạn styling vui vẻ!