Giới thiệu
Gradient Left to Right chuyển màu từ cạnh trái sang cạnh phải. Dùng từ khóa to right hoặc góc 90deg.
Cú pháp
/* Chuẩn hiện đại */ background: linear-gradient(to right, red, blue); /* Góc độ */ background: linear-gradient(90deg, red, blue); /* Cú pháp cũ (prefix) - lưu ý hướng ngược */ background: -webkit-linear-gradient(left, red, blue); /* left = từ trái sang phải */ background: -o-linear-gradient(right, red, blue); /* right = từ phải sang trái (ngược!) */ background: -moz-linear-gradient(right, red, blue); /* Firefox cũ cũng ngược */
Ví dụ: Red → Blue
<!DOCTYPE html>
<html>
<head>
<style>
#grad1 {
height: 100px;
width: 100%;
background: -webkit-linear-gradient(left, red, blue); /* Safari cũ */
background: -o-linear-gradient(right, red, blue); /* Opera cũ - NGƯỢC */
background: -moz-linear-gradient(right, red, blue); /* Firefox cũ - NGƯỢC */
background: linear-gradient(to right, red, blue); /* Chuẩn */
}
</style>
</head>
<body>
<div id="grad1"></div>
<p>Gradient từ đỏ (trái) → xanh (phải)</p>
</body>
</html>
⚠️ Cảnh báo: Cú pháp cũ có hướng NGƯỢC
| Cú pháp | Từ khóa | Hướng thực tế |
|---|---|---|
| Chuẩn (W3C) | to right | Trái → Phải ✓ |
| Chuẩn (W3C) | 90deg | Trái → Phải ✓ |
| -webkit- (cũ) | left | Trái → Phải ✓ |
| -webkit- (cũ) | right | Phải → Trái |
| -moz-/-o- (cũ) | left/right | Phải → Trái (NGƯỢC) |
Khuyến nghị: Chỉ dùng cú pháp chuẩn to right hoặc 90deg. Bỏ prefix cũ.
Color Stops
/* Phân bố đều */ linear-gradient(to right, red, yellow, blue) /* Tùy chỉnh % */ linear-gradient(to right, red 20%, yellow 50%, blue 80%) /* Hard stops - stripe */ linear-gradient(to right, red 50%, blue 50%) /* Rainbow bar */ linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet )
Ứng dụng thực tế
- Progress bar:
background: linear-gradient(to right, #4facfe, #00f2fe);+ animatebackground-size - Navigation indicator: Thanh chọn menu trượt ngang
- Skill bar: Gradient width thể hiện % skill
- Hero CTA: Gradient ngang thu hút
- Text gradient:
background: linear-gradient(to right, #667eea, #764ba2); -webkit-background-clip: text; -webkit-text-fill-color: transparent;
Ví dụ: Animated Progress Bar
<style>
.progress-bar {
height: 8px;
border-radius: 4px;
background: linear-gradient(to right, #4facfe, #00f2fe);
background-size: 200% 100%;
animation: progress-flow 2s linear infinite;
}
@keyframes progress-flow {
from { background-position: 200% 0; }
to { background-position: -200% 0; }
}
</style>
<div class="progress-bar"></div>