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

RGB vs RGBa สีใน CSS (คืออะไร ทำไม วิธีใช้)

เรียนรู้ความแตกต่างระหว่างสี RGB และ RGBa ใน CSS และวิธีใช้ RGBa สร้าง UI components สวยงาม ดึงดูดสายตา

RGB และ RGBa เป็นโมเดลสี 2 แบบใน CSS ใช้แทน Hex Code (เช่น #282828)

ความแตกต่างคืออะไร?

  • RGB = Red, Green, Blue
  • RGBa = Red, Green, Blue, และ Alpha

Alpha คือ transparency channel ควบคุมความโปร่งใสของสี

CSS มี 2 ฟังก์ชันสี: rgb() และ rgba()

ทั้งคู่ใช้ค่าสี 0-255 สำหรับ red, green, blue

แต่ rgb() ใช้สำหรับสีทึบ (solid) เท่านั้น:

{ /* 100% เขียวทึบ */ background-color: rgb(0, 255, 0); }

RGBa ยืดหยุ่นกว่า เพราะเพิ่ม transparency ผ่าน alpha channel:

{ /* 50% เขียวโปร่งใส */ background-color: rgba(0, 255, 0, 0.5); }

ทำไมต้องใส่ transparency ให้ background color?

เช่น อยากออกแบบ UI Card ดึงดูดสายตาแบบนี้:

RGB vs RGBa สีใน CSS (คืออะไร ทำไม วิธีใช้)

UI Card ประกอบด้วย:

  • Thumbnail image
  • Overlay
  • Text บนสุด

ใช้ rgba() ควบคุม alpha channel ให้เห็น background image เทียบกับข้อความ เลือก 50% ดำโปร่งใส:

.card-overlay { background-color: rgba(0, 0, 0, 0.5); /* 0.5 = 50% */ }

ทำไม 50%? อาจเป็น 40% หรือ 60% ก็ได้ หรือ linear-gradient 2 ระดับ โปร่งใส ขึ้นกับลุคที่ต้องการ

Alpha channel transparency สูง vs ต่ำ:

  • ค่า alpha ต่ำ (เช่น 0.1) = โปร่งใสมาก = เห็น background ชัด
  • ค่า alpha สูง (เช่น 0.9) = โปร่งใสน้อย = เห็น background น้อย

จากเปรียบเทียบด้านล่าง alpha channel ส่งผลต่อ readability และ mood:

RGB vs RGBa สีใน CSS (คืออะไร ทำไม วิธีใช้)

อย่าทำ overlay สว่างหรือมืดเกินไป ต้องหา sweet spot ที่สอดคล้องกับการนำเสนอเนื้อหา

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

HTML

 <div class="card"> <div class="card-overlay"></div> <img class="card-thumbnail" src="/images/the-north-sea-denmark.png" /> <div class="card-text"> <h3 class="card-title">The North Sea of Denmark</h3> <p class="card-description"> Explore the beautiful & dynamic North Sea of Denmark — where every day is a new experience. </p> </div> </div>

CSS

.card { position: relative; height: 400px; width: 400px; } .card-thumbnail { height: 100%; width: 100%; display: block; object-fit: cover; } .card-text { color: white; position: absolute; width: 80%; max-width: 300px; top: 70%; left: 50%; transform: translate(-50%, -50%); z-index: 1; } .card-title { font-size: 1.45rem; } .card-description { font-size: 1.15rem; margin-top: 0.5rem; line-height: 1.4; } .card-overlay { width: 100%; height: 100%; position: absolute; top: 0; left: 0; background-color: rgba(0, 0, 0, 0.5); z-index: 1; }

ใช้เป็น reference หรือจุดเริ่มต้นสำหรับ UI Cards ของตัวเอง