Linear gradient kết hợp với RGBA tạo hiệu ứng mờ dần (fade) hoặc trong suốt một phần.
Ví dụ mã nguồn
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
.linearGradient {
height: 200px;
width: 100%;
background-image: linear-gradient(
to left,
rgb(111, 0, 255), /* 100% opacity */
rgba(111, 0, 255, 0.616), /* ~62% opacity */
rgba(111, 0, 255, 0.384), /* ~38% opacity */
rgba(111, 0, 255, 0) /* 0% opacity (trong suốt hoàn toàn) */
);
border: 1px solid #ccc;
border-radius: 8px;
}
</style>
</head>
<body>
<h1>Linear Gradient với Transparency</h1>
<div class="linearGradient"></div>
<h2>Gradient trên chuyển từ tím đậm → trong suốt (từ phải sang trái)</h2>
</body>
</html>
Cú pháp Linear Gradient
/* Hướng */
linear-gradient(to right, red, blue) /* Trái → Phải */
linear-gradient(to bottom right, red, blue) /* Góc */
linear-gradient(45deg, red, blue) /* Góc độ (0deg = to top) */
/* Color stops với vị trí */
linear-gradient(red 0%, blue 50%, green 100%)
linear-gradient(red, blue 75%, green) /* Blue ở 75%, green 100% */
/* Transparency với RGBA/HSLA */
linear-gradient(rgba(255,0,0,1), rgba(255,0,0,0)) /* Đỏ → trong suốt */
linear-gradient(to right, #f00 0%, #f000 100%) /* Hex 8 digits (#RRGGBBAA) */
Repeating Linear Gradient
/* Sọc zebra */
.stripes {
background: repeating-linear-gradient(
45deg,
#fff, #fff 10px,
#f0f0f0 10px, #f0f0f0 20px
);
}
Ứng dụng thực tế
- Overlay text trên ảnh:
linear-gradient(to top, rgba(0,0,0,0.8), transparent) - Fade out content:
mask-image: linear-gradient(to bottom, black, transparent) - Loading shimmer:
repeating-linear-gradient(90deg, #f0f0f0, #e0e0e0)+ animation - Button gradient hover: transition background-position
Lưu ý
- Gradient là
background-image, không phải color → có thể kết hợp vớibackground-color - Hỗ trợ tốt mọi trình duyệt hiện đại (cần prefix -webkit- cho Safari cũ)
- In ấn: Gradient có thể không in đúng, cần test