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

Gradient Left to Right (Trái sang Phải) trong CSS3

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ápTừ khóaHướng thực tế
Chuẩn (W3C)to rightTrái → Phải ✓
Chuẩn (W3C)90degTrái → Phải ✓
-webkit- (cũ)leftTrái → Phải ✓
-webkit- (cũ)rightPhải → Trái
-moz-/-o- (cũ)left/rightPhả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); + animate background-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>