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

Gradient Top to Bottom (Trên xuống Dưới) trong CSS3

Giới thiệu

Gradient Top to Bottom là hướng mặc định của linear-gradient: màu chuyển từ cạnh trên xuống cạnh dưới. Không cần chỉ định hướng.

Cú pháp

/* Mặc định: to bottom (180deg) */
background: linear-gradient(color1, color2, ...);

/* Tường minh */
background: linear-gradient(to bottom, color1, color2);
background: linear-gradient(180deg, color1, color2);

Ví dụ: Pink → Green

<!DOCTYPE html>
<html>
<head>
  <style>
    #grad1 {
      height: 100px;
      width: 100%;
      background: -webkit-linear-gradient(pink, green);   /* Safari cũ */
      background: -o-linear-gradient(pink, green);        /* Opera cũ */
      background: -moz-linear-gradient(pink, green);      /* Firefox cũ */
      background: linear-gradient(pink, green);           /* Chuẩn */
    }
  </style>
</head>
<body>
  <div id="grad1"></div>
  <p>Gradient từ hồng (trên) → xanh lá (dưới)</p>
</body>
</html>

Color Stops cho Top-to-Bottom

/* 2 màu phân bố đều */
linear-gradient(pink, green)

/* 3 màu phân bố đều */
linear-gradient(pink, white, green)

/* Tùy chỉnh vị trí % */
linear-gradient(pink 0%, white 50%, green 100%)

/* Hard stop (chuyển đột ngột) */
linear-gradient(pink 50%, green 50%)

/* Multiple stops */
linear-gradient(
  #ff6b6b 0%,    /* Hồng */
  #feca57 25%,   /* Vàng */
  #48dbfb 50%,   /* Xanh nhạt */
  #ff6b6b 75%,   /* Hồng lại */
  #1dd1a1 100%   /* Xanh mint */
)

Ứng dụng thực tế

  • Hero section background: Brand color → lighter shade
  • Button hover: Darker shade top → lighter bottom (3D effect)
  • Card header: Subtle gradient cho depth
  • Progress bar: Animated background-position
  • Text gradient: background: linear-gradient(...); -webkit-background-clip: text; -webkit-text-fill-color: transparent;

Ví dụ: Button 3D effect với Top-to-Bottom

<style>
  .btn-3d {
    background: linear-gradient(to bottom, #4facfe 0%, #00f2fe 100%);
    border: none;
    border-bottom: 3px solid #00c9e8;
    border-radius: 8px;
    padding: 12px 24px;
    color: white;
    font-weight: 600;
    cursor: pointer;
    transition: transform 0.1s;
  }
  .btn-3d:active {
    transform: translateY(2px);
    border-bottom-width: 1px;
  }
</style>

Lưu ý Prefix

Hiện nay (2024) chỉ cần cú pháp chuẩn linear-gradient(...). Các prefix -webkit-, -moz-, -o- chỉ cần cho hỗ trợ trình duyệt rất cũ (trước 2013-2015).