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

วิธีสร้างรูปภาพพร้อมข้อความพื้นหลังโปร่งใส (Transparent Text Overlay) ด้วย CSS

วางข้อความบนรูปภาพพร้อมพื้นหลังโปร่งใส (Semi-transparent Background) ใช้ rgba() สำหรับสีพื้นหลังข้อความ

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

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * {    box-sizing: border-box; } body {    font-family: Arial;    font-size: 17px; } .imageContainer {    display: inline-block;    position: relative; } .imageContainer .imageContent {    position: absolute;    bottom: 0;    background: rgba(29, 6, 43, 0.5);    color: #f1f1f1;    width: 100%;    padding: 20px; } </style> </head> <body> <h2>Image with Transparent Text</h2> <div class="imageContainer"> <img src="https://i.picsum.photos/id/59/500/500.jpg"> <div class="imageContent"> <h1>Sceneray</h1>   <h3>A beautiful scenary showing fence, barbed wires and grass</h3> </div> </div> </body> </html>

หลักการ

  1. .imageContainer { position: relative; } - จุดอ้างอิง
  2. img - รูปภาพปกติ
  3. .imageContent { position: absolute; bottom: 0; width: 100%; } - ทับด้านล่างรูปเต็มความกว้าง
  4. background: rgba(29, 6, 43, 0.5) - สีม่วงเข้ม โปร่งใส 50%

รูปแบบอื่นๆ

  • Top Overlay: top: 0 แทน bottom: 0
  • Center Overlay: top: 50%; left: 50%; transform: translate(-50%, -50%);
  • Full Overlay: top: 0; left: 0; right: 0; bottom: 0;

ผลลัพธ์

รูปทิวทัศน์ พร้อมแถบสีม่วงโปร่งใสด้านล่าง เขียน "Sceneray" และคำอธิบาย สีขาว