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

จัดตำแหน่งข้อความมุมล่างขวาบนรูปภาพด้วย CSS


หลักการทำงาน

เหมือนกับมุมล่างซ้าย แต่เปลี่ยนจาก left เป็น right ใช้ Relative Positioning บนคอนเทนเนอร์ และ Absolute Positioning บนข้อความ

ขั้นตอนสำคัญ

  1. คอนเทนเนอร์: position: relative
  2. รูปภาพ: width: 100%; height: auto
  3. ข้อความ: position: absolute; bottom: 10px; right: 19px;

ตัวอย่างการใช้งาน

<!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;
      right: 20px;           /* เปลี่ยนจาก left เป็น right */
      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>

สรุปตำแหน่งทั้ง 4 มุม + กึ่งกลาง

ตำแหน่ง CSS Properties
มุมบนซ้าย top: 10px; left: 10px;
มุมบนขวา top: 10px; right: 10px;
มุมล่างซ้าย bottom: 10px; left: 10px;
มุมล่างขวา bottom: 10px; right: 10px;
กึ่งกลาง top: 50%; left: 50%; transform: translate(-50%, -50%);

คลาสยูทิลิตี้สำหรับใช้งานจริง (Utility Classes)

.img-overlay {
  position: relative;
  display: inline-block;
  max-width: 100%;
}

.img-overlay img {
  width: 100%;
  height: auto;
  display: block;
}

.overlay-text {
  position: absolute;
  padding: 8px 12px;
  font-size: 14px;
  color: white;
  background: rgba(0,0,0,0.6);
  border-radius: 4px;
  font-weight: 500;
}

/* ตำแหน่งต่างๆ */
.overlay-top-left     { top: 10px; left: 10px; }
.overlay-top-right    { top: 10px; right: 10px; }
.overlay-bottom-left  { bottom: 10px; left: 10px; }
.overlay-bottom-right { bottom: 10px; right: 10px; }
.overlay-center       { top: 50%; left: 50%; transform: translate(-50%, -50%); }

การใช้งาน

<div class="img-overlay">
  <img src="photo.jpg" alt="Description">
  <span class="overlay-text overlay-bottom-right">มุมล่างขวา</span>
</div>

คำแนะนำ

  • ใช้ rgba(0,0,0,0.5-0.7) สำหรับพื้นหลังข้อความ เพื่ออ่านง่ายบนรูปภาพทุกประเภท
  • เพิ่ม text-shadow เพื่อความคอนทราสต์เพิ่มเติม
  • ใช้ display: inline-block บนคอนเทนเนอร์ เพื่อไม่ให้กว้างกว่ารูปภาพ