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

การจัดกึ่งกลางแนวนอนและแนวตั้งด้วย Flexbox ใน CSS3

Flexbox Centering: จัดกึ่งกลางสมบูรณ์แบบ 2 แกน

ใช้ display: flex + justify-content: center (main axis) + align-items: center (cross axis) จัด child ให้อยู่กึ่งกลาง container ทั้งแนวนอนและแนวตั้ง

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

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .h-container {
      display: flex; width: 300px; height: 300px;
      background-color: lightblue; justify-content: center; align-items: center;
      border: 2px solid black;
    }
    .h-1 { font-size: 30px; width: 150px; height: 150px; background-color: red; color: white; border: 2px solid rgb(58, 2, 83); }
  </style>
</head>
<body>
  <h2>Horizontal and Vertical Center Alignment using Flexbox</h2>
  <div class="h-container"><div class="h-1">Centered Div</div></div>
</body>
</html>

เงื่อนไข

  • Container ต้องมีขนาด (width/height หรือ min-height)
  • Default flex-direction: row → main axis = horizontal, cross axis = vertical
  • ถ้า flex-direction: column → main axis = vertical, cross axis = horizontal (justify/align สลับบทบาท)

Grid Alternative (สั้นกว่า)

.centered {
  display: grid;
  place-items: center; /* = justify-items: center + align-items: center */
  min-height: 100vh;
}

Absolute + Transform (Legacy)

.centered {
  position: relative; /* หรือ parent relative */
}
.child {
  position: absolute; top: 50%; left: 50%;
  transform: translate(-50%, -50%);
}

Flexbox/Grid เป็นมาตรฐานปัจจุบัน – ใช้ง่าย Responsive ได้ ไม่ต้องคำนวณ