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

ฟังก์ชัน CSS linear-gradient() สำหรับไล่สีเส้นตรง

ฟังก์ชัน linear-gradient() ใช้สำหรับกำหนดไล่สีเส้นตรง (linear gradient) เป็นภาพพื้นหลัง:

background-image: linear-gradient(direction, color-stop1, color-stop2, ...);

กำหนดจุดเริ่มต้นและทิศทาง พร้อมสีหยุด (color stops) เพื่อสร้างการเปลี่ยนสีเรียบเนียน

ตัวอย่างที่ 1: ไล่สีทแยงมุม (to bottom right)

<!DOCTYPE html> <html> <head> <style> div {    text-align: justify;    text-justify: inter-word;    color: white;    background-image: linear-gradient(to bottom right, red, blue);    position: absolute;    right: 90px; } </style> </head> <body> <h2>Demo Heading</h2> <div>This is demo text... </div> </body> </html>

ผลลัพธ์

ฟังก์ชัน CSS linear-gradient() สำหรับไล่สีเส้นตรง

ตัวอย่างที่ 2: ไล่สีหลายสี (Rainbow)

<!DOCTYPE html> <html> <head> <style> body {    background-image: linear-gradient(to right, yellow, orange, yellow, green, blue, indigo, violet); } .demo {    text-decoration: overline;    text-decoration-color: yellow;    font-size: 1.3em; } </style> </head> <body> <h1>Examination Details</h1> <p class="demo">Exam on 20th December.</p> <p class="demo2">Exam begins at 9AM.</p> </body> </html>

ผลลัพธ์

ฟังก์ชัน CSS linear-gradient() สำหรับไล่สีเส้นตรง

ไวยากรณ์และค่าทิศทาง

/* ทิศทางด้วยคำสั่ง */
linear-gradient(to bottom, red, blue)
linear-gradient(to top right, red, blue)
linear-gradient(to left, red, blue)

/* ทิศทางด้วยองศา (0deg = ขึ้นบน, 90deg = ขวา) */
linear-gradient(45deg, red, blue)
linear-gradient(135deg, red, blue)

/* หลายสีหยุด พร้อมตำแหน่ง */
linear-gradient(red, yellow 30%, green 60%, blue)

คำแนะนำ

  • ใช้ repeating-linear-gradient() สำหรับรูปแบบซ้ำ
  • รองรับความโปร่งใสด้วย rgba() หรือ hsla()
  • เก่ากว่าอาจต้องใช้ prefix: -webkit-linear-gradient()