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

Thêm độ trong suốt (transparency) cho nút bấm với CSS opacity

Sử dụng thuộc tính opacity (0 đến 1) để tạo độ trong suốt cho nút bấm. Giá trị 0.5-0.8 thường dùng cho trạng thái disabled hoặc hover subtle.

Ví dụ: opacity cho trạng thái disabled

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

Các mức opacity thường dùng

Giá trịỨng dụng
1 (mặc định)Bình thường, hoàn toàn không trong suốt
0.8Hover subtle, secondary action
0.6Disabled state (chuẩn)
0.5Disabled mạnh, overlay background
0.3-0.4Skeleton loading, placeholder
0Ẩn hoàn toàn (vẫn chiếm không gian)

Opacity vs rgba/hsla vs background-alpha

Phương phápẢnh hưởngUse case
opacity: 0.5Cả element + children (text, icon)Disabled toàn bộ component
background: rgba(0,0,0,0.5)Chỉ backgroundOverlay, modal backdrop
color: rgba(255,255,255,0.7)Chỉ text colorMuted text, placeholder
border-color: rgba(...)Chỉ borderSubtle borders

Accessibility cho Disabled Button

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

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
/* Đảm bảo contrast ratio ≥ 4.5:1 ngay cả khi opacity giảm */

Lưu ý

  • opacity làm mờ toàn bộ element (kể cả text, icon, border)
  • Dùng rgba()/hsla() nếu chỉ muốn trong suốt background
  • Kết hợp pointer-events: none cho disabled thật sự
  • Transition opacity cho mượt mà: transition: opacity 0.2s