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

Tạo Linear Gradient nhiều Color Stops với CSS

Linear gradient hỗ trợ nhiều color stops (điểm dừng màu) để tạo cầu vồng, spectrum, hoặc chuyển màu phức tạp.

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, orange, blue, green, pink, yellow);
    border-radius: 8px;
    border: 1px solid #ddd;
  }
  .linearGradientStops {
    height: 200px;
    width: 100%;
    margin-top: 20px;
    background-image: linear-gradient(
      to right,
      red 0%,
      orange 15%,
      yellow 30%,
      green 45%,
      cyan 60%,
      blue 75%,
      purple 90%,
      magenta 100%
    );
    border-radius: 8px;
    border: 1px solid #ddd;
  }
</style>
</head>
<body>
<h1>Linear Gradient Multiple Color Stops</h1>
<h3>Tự động chia đều (5 màu)</h3>
<div class="linearGradient"></div>
<h3>Tùy chỉnh vị trí color stops (Cầu vồng)</h3>
<div class="linearGradientStops"></div>
</body>
</html>

Cách xác định vị trí Color Stops

  • Không chỉ định vị trí: Màu được phân bố đều (0%, 25%, 50%, 75%, 100% cho 5 màu)
  • Chỉ định %: red 20%, blue 80% - kiểm soát chính xác
  • Chỉ định length: red 50px, blue 200px - ít dùng cho responsive
  • Trùng vị trí: red 50%, blue 50% - chuyển màu gắt (hard stop)

Hard Stops (Chuyển màu gắt)


.hard-stops {
  background: linear-gradient(
    to right,
    red 33.33%, orange 33.33%,
    orange 66.66%, yellow 66.66%,
    yellow 100%
  );
  /* Tạo 3 dải màu ngang bằng nhau, không blur */
}

Gradient Text (Chữ gradient)


.gradient-text {
  background: linear-gradient(45deg, #ff6b6b, #feca57, #48dbfb, #ff9ff3, #54a0ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  font-size: 3rem; font-weight: bold;
}

Animated Gradient (Background position animation)


.animated-gradient {
  background: linear-gradient(90deg, #ff6b6b, #feca57, #48dbfb, #ff6b6b);
  background-size: 300% 100%;
  animation: gradientShift 3s ease infinite;
}
@keyframes gradientShift {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}