หลักการทำงาน
ใช้ Relative Positioning บนคอนเทนเนอร์ และ Absolute Positioning บนข้อความ เพื่อจัดตำแหน่งข้อความบนรูปภาพได้อย่างแม่นยำ
ขั้นตอนสำคัญ
- คอนเทนเนอร์:
position: relative - รูปภาพ:
width: 100%เพื่อตอบสนองตามขนาดคอนเทนเนอร์ - ข้อความ:
position: absolute+bottom+left
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<head>
<style>
.box {
position: relative;
display: inline-block; /* ปรับขนาดตามรูปภาพ */
max-width: 100%;
}
.box img {
width: 100%;
height: auto;
opacity: 0.6; /* ทำให้รูปจางลง เพื่อให้ข้อความอ่านง่าย */
display: block;
}
.direction {
position: absolute;
bottom: 15px;
left: 20px;
font-size: 16px;
color: white;
font-weight: bold;
text-shadow: 1px 1px 2px rgba(0,0,0,0.7);
padding: 5px 10px;
background-color: rgba(0,0,0,0.5);
border-radius: 4px;
}
</style>
</head>
<body>
<h1>จัดตำแหน่งข้อความมุมล่างซ้าย</h1>
<p>รูปภาพด้านล่างมีข้อความอยู่ที่มุมล่างซ้าย:</p>
<div class="box">
<img src="https://www.tutorialspoint.com/python/images/python_data_science.jpg" alt="Python Data Science">
<div class="direction">มุมล่างซ้าย</div>
</div>
</body>
</html>
ตำแหน่งอื่นๆ ที่นิยมใช้
| ตำแหน่ง | CSS Properties |
|---|---|
| มุมบนซ้าย | top: 10px; left: 10px; |
| มุมบนขวา | top: 10px; right: 10px; |
| มุมล่างขวา | bottom: 10px; right: 10px; |
| กึ่งกลาง | top: 50%; left: 50%; transform: translate(-50%, -50%); |
คำแนะนำ
- ใช้
rgba()หรือopacityสำหรับพื้นหลังข้อความ เพื่อความอ่านง่าย - เพิ่ม
text-shadowเพื่อให้ข้อความโดดเด่นบนพื้นหลังซับซ้อน - ใช้
max-width: 100%บนรูปภาพเพื่อ Responsive Design