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

วิธีจัดตำแหน่งองค์ประกอบให้อยู่กึ่งกลางแนวตั้งและแนวนอนด้วย CSS

Flexbox Centering สำหรับองค์ประกอบทั่วไป

เทคนิคเดียวกับการจัดปุ่ม แต่อาจเป็นข้อความ, รูปภาพ, การ์ด หรือ container ย่อย ใช้ display: flex + justify-content: center + align-items: center

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

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .centered {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200px;
      border: 3px solid rgb(0, 70, 128);
    }
  </style>
</head>
<body>
  <h1>ตัวอย่าง Centering</h1>
  <div class="centered">
    <h2>ข้อความนี้อยู่กึ่งกลางแนวตั้งและแนวนอน</h2>
  </div>
</body>
</html>

จุดสำคัญ

  • Container ต้องมี height (หรือ min-height)
  • Child ใดๆ ก็ตามใน flex container จะถูกจัดกึ่งกลางอัตโนมัติ
  • หากมีหลาย child จะเรียงติดกันกึ่งกลาง – ใช้ flex-direction: column + gap เพื่อเว้นระยะ

แนวทางปัจจุบันแนะนำ

.centered {
  display: grid;
  place-items: center; /* จัดกึ่งกลางทั้ง 2 แกนในบรรทัดเดียว */
  min-height: 100vh; /* หรือความสูงที่ต้องการ */
}

Grid place-items: center สั้นกว่า และ readable มากขึ้น ใช้ได้ทุกที่ที่รองรับ CSS Grid