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

วางปุ่มบนรูปภาพ (Button on Image) ด้วย CSS


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

ใช้ Relative Positioning บนคอนเทนเนอร์รูปภาพ และ Absolute Positioning บนปุ่ม พร้อม transform: translate(-50%, -50%) เพื่อจัดให้ปุ่มอยู่ กึ่งกลางพอดี ไม่ว่าขนาดปุ่มจะเป็นเท่าไหร่

เทคนิคสำคัญ: Centering ด้วย Transform

.btn-centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);  /* ย้ายกลับครึ่งหนึ่งของขนาดตัวเอง */
}

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

<!DOCTYPE html>
<html>
<head>
  <style>
    .box {
      position: relative;
      width: 100%;
      max-width: 400px;        /* จำกัดขนาดสูงสุด */
      margin: 20px auto;
    }
    .box img {
      width: 100%;
      height: auto;
      display: block;
      border-radius: 8px;
    }
    .box .btn {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      padding: 12px 28px;
      background-color: #007bff;
      color: white;
      border: none;
      border-radius: 30px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      box-shadow: 0 4px 12px rgba(0,0,0,0.3);
      transition: all 0.3s ease;
    }
    .box .btn:hover {
      background-color: #0056b3;
      transform: translate(-50%, -50%) scale(1.05);
      box-shadow: 0 6px 20px rgba(0,0,0,0.4);
    }
  </style>
</head>
<body>
  <div class="box">
    <img src="https://www.tutorialspoint.com/videotutorials/images/current_affairs_home.jpg" alt="Current Affairs">
    <button class="btn">เริ่มต้นเลย</button>
  </div>
</body>
</html>

ตำแหน่งปุ่มอื่นๆ บนรูปภาพ

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

ตัวอย่าง: Overlay เนื้อหาเต็มรูป + ปุ่มกึ่งกลาง

.image-card {
  position: relative;
  border-radius: 12px;
  overflow: hidden;
}

.image-card img {
  width: 100%;
  height: 300px;
  object-fit: cover;
}

.image-card::before {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
  z-index: 1;
}

.image-card .content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24px;
  color: white;
  z-index: 2;
}

.image-card .btn {
  margin-top: 16px;
  padding: 12px 24px;
  background: white;
  color: #333;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
}

คำแนะนำ

  • ใช้ transform: translate(-50%, -50%) เพื่อจัดกึ่งกลางแม่นยำ ไม่ต้องรู้ขนาดปุ่มล่วงหน้า
  • เพิ่ม max-width บนคอนเทนเนอร์ เพื่อไม่ให้รูปใหญ่เกินหน้าจอ
  • ใช้ z-index จัดลำดับชั้น: รูป (1) → Overlay (2) → ปุ่ม/ข้อความ (3)
  • เพิ่ม transition สำหรับ hover effect ที่นุ่มนวล
  • สำหรับ Accessibility: ใช้ <button> จริง ไม่ใช่ div