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.8 | Hover subtle, secondary action |
0.6 | Disabled state (chuẩn) |
0.5 | Disabled mạnh, overlay background |
0.3-0.4 | Skeleton 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ưởng | Use case |
opacity: 0.5 | Cả element + children (text, icon) | Disabled toàn bộ component |
background: rgba(0,0,0,0.5) | Chỉ background | Overlay, modal backdrop |
color: rgba(255,255,255,0.7) | Chỉ text color | Muted text, placeholder |
border-color: rgba(...) | Chỉ border | Subtle 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