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

Sắp xếp màu tuyến tính với CSS3 Gradients

Giới thiệu

Linear Gradient sắp xếp 2+ màu theo đường thẳng. Đây là loại gradient cơ bản và phổ biến nhất, dùng cho background, border, text, mask, v.v.

Cú pháp chuẩn

linear-gradient([<angle> | to <side-or-corner>], <color-stop>[, <color-stop>]+)

Ví dụ cơ bản: Pink → Green

<!DOCTYPE html>
<html>
<head>
  <style>
    #grad1 {
      height: 100px;
      width: 100%;
      background: -webkit-linear-gradient(pink, green);
      background: -o-linear-gradient(pink, green);
      background: -moz-linear-gradient(pink, green);
      background: linear-gradient(pink, green);
    }
  </style>
</head>
<body>
  <div id="grad1"></div>
</body>
</html>

Output (Minh họa)

Sắp xếp màu tuyến tính với CSS3 Gradients

Các biến thể hướng

HướngCú phápGóc độ
Trên → Dưới (mặc định)linear-gradient(a, b) / to bottom180deg
Dưới → Trênto top0deg / 360deg
Trái → Phảito right90deg
Phải → Tráito left270deg
Trên trái → Dưới phảito bottom right~135deg
Dưới trái → Trên phảito top right~45deg

Color Stops nâng cao

/* Vị trí % */
linear-gradient(red 10%, yellow 50%, blue 90%)

/* Hard line (stripe) */
linear-gradient(red 50%, blue 50%)

/* Transparency */
linear-gradient(rgba(255,0,0,1), rgba(255,0,0,0))

/* Multiple stops cùng vị trí */
linear-gradient(red 30%, orange 30%, yellow 60%, green 60%)

Ứng dụng: Text Gradient (Chữ gradient)

<style>
  .gradient-text {
    background: linear-gradient(to right, #667eea, #764ba2);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    color: transparent; /* Fallback */
    font-size: 3rem;
    font-weight: 800;
  }
</style>

<h1 class="gradient-text">Gradient Text</h1>

Ứng dụng: Border Gradient

<style>
  .gradient-border {
    border: 3px solid transparent;
    border-image: linear-gradient(to right, #667eea, #764ba2) 1;
    border-radius: 8px;
  }
</style>

Lưu ý trình duyệt cũ

  • Prefix -webkit-, -moz-, -o- chỉ cần cho IE10-, Safari 6-, Android 4.4-
  • Production 2024+: Chỉ cần linear-gradient(...) chuẩn
  • Fallback solid color: background: #667eea; background: linear-gradient(...);