align-content: center คืออะไร?
ค่า center ของ align-content จัดกลุ่ม Flex Lines (บรรทัดทั้งหมด) ให้อยู่ กึ่งกลางของ Cross Axis พื้นที่ว่างจะถูกแบ่งเท่าๆ กันระหว่างขอบบนและขอบล่าง
เงื่อนไขการทำงาน
display: flex+flex-wrap: wrap- คอนเทนเนอร์มีขนาด Cross Axis มากกว่าความสูง/กว้างรวมของทุกบรรทัด
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<head>
<style>
.mycontainer {
display: flex;
height: 200px; /* ความสูงจำกัด */
background-color: #ffebee;
align-content: center; /* จัดบรรทัดกึ่งกลางแนวตั้ง */
flex-wrap: wrap; /* สำคัญ: ต้อง wrap */
padding: 10px;
}
.mycontainer > div {
background-color: #ffc107;
color: #333;
text-align: center;
line-height: 60px;
font-size: 24px;
width: 100px;
margin: 5px;
border-radius: 4px;
}
</style>
</head>
<body>
<h1>ตัวอย่าง align-content: center</h1>
<p>บรรทัดทั้งหมด (3 บรรทัด) จะอยู่กึ่งกลางแนวตั้งของ container (200px)</p>
<div class="mycontainer">
<div>Q1</div>
<div>Q2</div>
<div>Q3</div>
<div>Q4</div>
<div>Q5</div>
<div>Q6</div>
<div>Q7</div>
<div>Q8</div>
</div>
</body>
</html>
ภาพแสดงผล
Container: 200px height, 3 lines × 60px = 180px used, 20px free align-content: center ┌────────────────────┐ │ (10px) │ ← พื้นที่ว่างบน = 10px ├────────────────────┤ │ ▓▓ ▓▓ ▓▓ │ ← Line 1 │ ▓▓ ▓▓ ▓▓ │ ← Line 2 │ ▓▓ ▓▓ │ ← Line 3 ├────────────────────┤ │ (10px) │ ← พื้นที่ว่างล่าง = 10px └────────────────────┘
เปรียบเทียบ align-content ทั้ง 7 ค่า
| ค่า | พื้นที่ขอบบน/ล่าง | พื้นที่ระหว่างบรรทัด |
|---|---|---|
| flex-start | 0 / ทั้งหมด | 0 |
| flex-end | ทั้งหมด / 0 | 0 |
| center | ครึ่งหนึ่ง / ครึ่งหนึ่ง | 0 |
| space-between | 0 / 0 | เท่าๆ กัน |
| space-around | 0.5x / 0.5x | 1x |
| space-evenly | 1x / 1x | 1x |
| stretch | N/A (ยืดบรรทัด) | N/A |
การใช้งานจริง: Card Grid จัดกึ่งกลาง
.card-grid {
display: flex;
flex-wrap: wrap;
align-content: center; /* บรรทัด cards อยู่กึ่งกลางแนวตั้ง */
justify-content: center; /* cards ในแต่ละบรรทัดกึ่งกลางแนวนอน */
gap: 24px;
padding: 40px 24px;
min-height: 600px; /* ต้องมีความสูงขั้นต่ำ */
}
.card {
flex: 0 1 300px; /* ไม่ขยาย, บีบได้, basis 300px */
background: white;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
การใช้งานจริง: Modal / Dialog Centering
.modal-overlay {
display: flex;
align-content: center; /* จัดกึ่งกลางแนวตั้ง */
justify-content: center; /* จัดกึ่งกลางแนวนอน */
position: fixed;
inset: 0;
background: rgba(0,0,0,0.5);
}
.modal-content {
background: white;
border-radius: 12px;
padding: 32px;
max-width: 500px;
width: 90%;
/* ไม่ต้องใช้ transform: translate(-50%, -50%) แล้ว! */
}
คำแนะนำ
- ใช้
centerเมื่อต้องการเนื้อหากลุ่มอยู่กึ่งกลางพื้นที่ว่าง - ร่วมกับ
justify-content: centerสำหรับจัดกึ่งกลางทั้ง 2 แกน (Centering) - ต้องมี
flex-wrap: wrapและความสูงจำกัดของ container - สำหรับ single-line centering ให้ใช้
align-items: centerแทน