Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Tạo nút bấm (button) trạng thái disabled với CSS

Để tạo giao diện nút bấm bị vô hiệu hóa (disabled), sử dụng thuộc tính opacity để làm mờ nút, kết hợp với cursor: not-allowed và loại bỏ hiệu ứng hover.

Ví dụ cơ bản

<!DOCTYPE html>
<html>
<head>
  <style>
    .btn {
      color: #333;
      text-align: center;
      font-size: 15px;
      padding: 12px 24px;
      border: none;
      border-radius: 4px;
      background-color: #3498db;
      color: white;
      cursor: pointer;
      transition: opacity 0.2s, background 0.2s;
    }
    .btn:disabled,
    .btn.disabled {
      opacity: 0.5;
      cursor: not-allowed;
      pointer-events: none;
    }
    .btn:hover:not(:disabled) {
      background-color: #2980b9;
    }
  </style>
</head>
<body>
  <h2>Kết quả</h2>
  <p>So sánh nút bình thường và nút disabled:</p>
  <button class="btn">Kích hoạt</button>
  <button class="btn" disabled>Vô hiệu hóa</button>
  <button class="btn disabled">Disabled qua class</button>
</body>
</html>

Các phương pháp tạo trạng thái disabled

Phương phápƯu điểmNhược điểm
disabled attributeNgăn chặn submit form, không focus được, semanticKhông thể style pseudo-class :hover
Class .disabled + aria-disabled="true"Kiểm soát hoàn toàn style, vẫn focus đượcCần JS ngăn chặn sự kiện click
pointer-events: noneVô hiệu hóa hoàn toàn tương tác chuộtKhông ngăn phím Tab/Enter, cần kết hợp

Best Practice: Accessible Disabled Button

<button class="btn" disabled aria-disabled="true">
  Đang xử lý...
</button>

.btn:disabled {
  opacity: 0.6;
  background: #bdc3c7;
  color: #7f8c8d;
  cursor: not-allowed;
}

Lưu ý quan trọng

  • Luôn dùng thuộc tính disabled (HTML) thay vì chỉ class cho form submit
  • Kết hợp aria-disabled="true" cho screen reader
  • Đảm bảo độ tương phản màu vẫn đủ (WCAG) ngay cả khi opacity giảm
  • Thêm transition cho mượt mà khi chuyển trạng thái