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

วิธีวาง Text Block บนรูปภาพ (Image Text Overlay) ด้วย CSS

เทคนิคการวางบล็อกข้อความ (Text Block) บนรูปภาพที่ตำแหน่งเฉพาะ (มุมล่างขวา) ใช้ Position Absolute

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

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .imageContainer {    display: inline-block;    position: relative;    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif } .captionBlock {    position: absolute;    bottom: 20px;    right: 20px;    background-color: rgb(14, 0, 94);    color: rgb(255, 255, 255);    padding-left: 20px;    padding-right: 20px;    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } </style> </head> <body> <h1>Image Text Block Example</h1> <div class="imageContainer"> <img src="https://i.picsum.photos/id/59/500/500.jpg" alt="Nature" style="width:100%;"> <div class="captionBlock"> <h3>Scenary</h3> <h4>Fence on the ground</h4> </div> </div> </body> </html>

คำอธิบาย

  • .imageContainer { position: relative; display: inline-block; } - ครอบรูปภาพ จุดอ้างอิง
  • img { width: 100%; } - รูปขยายเต็ม Container
  • .captionBlock { position: absolute; bottom: 20px; right: 20px; } - วางมุมล่างขวา ห่าง 20px
  • พื้นหลังสีม่วงเข้ม ขาวตัวอักษร Padding ซ้าย-ขวา 20px

ตำแหน่งอื่นๆ ที่นิยม

ตำแหน่งCSS
Top Lefttop: 20px; left: 20px;
Top Righttop: 20px; right: 20px;
Bottom Leftbottom: 20px; left: 20px;
Centertop: 50%; left: 50%; transform: translate(-50%, -50%);

ผลลัพธ์

รูปทิวทัศน์ มุมล่างขวา มีกล่องสีม่วงเข้ม เขียน "Scenary" และ "Fence on the ground"