Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

การตั้งค่าตำแหน่ง Color Stops ใน CSS

Gradient Color Stops Position: ควบคุมตำแหน่งสีเปลี่ยนด้วย % หรือ Length

ใน linear-gradient() และ radial-gradient()color position (%, px, em) ควบคุมการกระจายสีได้ละเอียด

โค้ดตัวอย่าง

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .even {
      height: 100px;
      background-image: linear-gradient(rgb(61, 255, 2), rgb(0, 174, 255), rgb(255, 29, 29));
    }
    .uneven {
      height: 100px;
      background-image: linear-gradient(
        rgb(61, 255, 2) 40%,
        rgb(0, 174, 255) 80%,
        rgb(255, 29, 29) 20%
      );
    }
  </style>
</head>
<body>
  <h1>Linear Gradient Location Color Stops</h1>
  <h3>Evenly Spaced (default)</h3> <div class="even"></div>
  <h3>Unevenly Spaced (custom positions)</h3> <div class="uneven"></div>
</body>
</html>

Color Stop Position Rules

  • ไม่ระบุตำแหน่ง: browser แบ่งเท่าๆ กัน (0%, 50%, 100% สำหรับ 3 สี)
  • ระบุ %: red 20%, blue 80%
  • ระบุ length: red 50px, blue 200px (จากจุดเริ่มต้น gradient)
  • ตำแหน่งต้องไม่ลดลง: red 40%, blue 20% จะถูกแก้ไขเป็น 40% ทั้งคู่ (hard stop)
  • ซ้ำได้: red 20%, red 40%, blue 40%, blue 60% (hard transition)

Hard Stops (สีเปลี่ยนทันที)

.stripes {
  background: linear-gradient(
    to right,
    red 0%, red 20%,
    orange 20%, orange 40%,
    yellow 40%, yellow 60%,
    green 60%, green 80%,
    blue 80%, blue 100%
  );
}

Repeating Gradient

.pattern {
  background: repeating-linear-gradient(
    45deg,
    #fff 0, #fff 10px,
    #eee 10px, #eee 20px
  );
}