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

วิธีเพิ่ม Text Gradient Color ด้วย CSS

เรียนรู้เพิ่ม linear gradient color ให้ text elements ด้วย CSS และหลีกเลี่ยงข้อผิดพลาดทั่วไป

ต้องใช้ CSS properties 3 ตัว:

  • background
  • -webkit-background-clip
  • -webkit-text-fill-color

ทำไมใช้ background property สำหรับสีข้อความ? วิธีนี้ดู hacky แต่ทำงานได้จริง!

ตัวอย่าง: linear gradient ซ้ายไปขวา บน text element สีส้มและแดง:

HTML

<h2> heading พร้อม class text-gradient:

<h2 class="text-gradient">Gradient text color!</h2>

CSS

เพิ่ม gradient styles ให้ .text-gradient:

.text-gradient { background: linear-gradient(to right, #ff8a00 0%, #dd4c4f 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }

ผลลัพธ์:

Gradient text color!

ดูดีนะ!

แตะรอสักครู่!

สังเกตปัญหาไหม? สีถูก apply ไม่สม่ำเสมอ

linear-gradient รับ 2 สี:

  • #ff8a00 (ส้ม)
  • #DD4C4F (แดง)

ควรกระจาย 0-100% สม่ำเสมอ ตาม CSS:

(to right, #ff8a00 0%, #DD4C4F 100%)

แตะ text example เกือบส้มหมด:

Gradient text color!

Tip: toggle dark mode (ไอคอนพระจันทร์) จะเห็นชัดขึ้น

เพราะ <h2> เป็น block-level element default background ครอบ full width ของ parent container

ทำให้สี gradient stretch กว้างกว่าข้อความ เพราะ target background property

เพิ่ม border ให้ text example เพื่อให้เห็นชัด:

Gradient text color!

เห็นไหม? Text gradients ควรอยู่บน text เท่านั้น ไม่ใช่ background (แต่เราต้องใช้ background property)

แก้ด้วยการ override display:block default ของ <h2> เป็น inline-block:

.text-gradient { background: linear-gradient(to right, #ff8a00 0%, #dd4c4f 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; display: inline-block; }

ผลลัพธ์:

Gradient text color!

เยี่ยม! ตอนนี้สีแดงเด่นเท่าส้ม เพราะกระจาย 50-50

Browser Compatibility

Gradient color trick รองรับแค่ WebKit browsers เบราว์เซอร์อื่นใช้ CSS color property เป็น fallback สีใกล้เคียง gradient