align-items คืออะไร?
คุณสมบัติ align-items ควบคุมการจัดเรียง flex items บน Cross Axis (แกนตั้งฉากกับ Main Axis) ภายใน บรรทัดเดียว (single line) ทำงานร่วมกับ flex-direction
ค่าทั้ง 5 ค่า
| ค่า |
พฤติกรรม |
Row (default) |
Column |
stretch (default) |
ยืดเต็มความสูง/กว้าง Cross Axis |
ยืดสูงเท่าคอนเทนเนอร์ |
ยืดกว้างเท่าคอนเทนเนอร์ |
flex-start |
ชิดจุดเริ่มต้น Cross Axis |
ชิดบน |
ชิดซ้าย |
flex-end |
ชิดจุดสิ้นสุด Cross Axis |
ชิดล่าง |
ชิดขวา |
center |
กึ่งกลาง Cross Axis |
กึ่งกลางแนวตั้ง |
กึ่งกลางแนวนอน |
baseline |
จัดตาม baseline ของข้อความ |
จัด baseline แนวนอน |
จัด baseline แนวตั้ง |
ตัวอย่าง: align-items: center
<!DOCTYPE html>
<html>
<head>
<style>
.mycontainer {
display: flex;
background-color: #fff3e0;
align-items: center; /* จัดกึ่งกลางแนวตั้ง (cross axis) */
height: 150px; /* ต้องมีความสูงจำกัด */
width: 600px;
padding: 10px;
}
.mycontainer > div {
background-color: white;
border: 2px solid #ff9800;
text-align: center;
line-height: 40px;
font-size: 20px;
width: 100px;
margin: 5px;
border-radius: 4px;
}
</style>
</head>
<body>
<h1>ตัวอย่าง align-items: center</h1>
<div class="mycontainer">
<div>Q1</div>
<div>Q2</div>
<div>Q3</div>
<div>Q4</div>
</div>
</body>
</html>
ตัวอย่างเปรียบเทียบ: flex-direction: row vs column
/* Row direction (default) - Cross Axis = Vertical */
.row-container {
display: flex;
flex-direction: row;
height: 200px;
align-items: center; /* จัดกึ่งกลาง "แนวตั้ง" */
}
/* Column direction - Cross Axis = Horizontal */
.column-container {
display: flex;
flex-direction: column;
width: 300px;
align-items: center; /* จัดกึ่งกลาง "แนวนอน" */
}
กรณีพิเศษ: baseline
.baseline-container {
display: flex;
align-items: baseline; /* จัดตาม baseline ของข้อความแรก */
}
.baseline-container .item {
font-size: 16px; /* baseline ตรงกัน */
}
.baseline-container .large {
font-size: 32px; /* baseline ยังคงตรงกัน แต่ข้อความใหญ่กว่า */
}
align-items vs align-self vs align-content
| คุณสมบัติ |
ระดับ |
ผลกระทบ |
เงื่อนไข |
| align-items |
Container |
Items ทั้งหมดในบรรทัด |
ทำงานเสมอ |
| align-self |
Item |
Item เดียว (override) |
ทำงานเสมอ |
| align-content |
Container |
บรรทัดทั้งหมด (flex lines) |
ต้องมี flex-wrap + multi-line |
การใช้งานจริง: Vertically Center Content
.center-both {
display: flex;
justify-content: center; /* Main axis */
align-items: center; /* Cross axis */
height: 100vh;
}
/* หรือใช้ shorthand */
.center-both {
display: flex;
place-content: center; /* justify-content + align-content */
place-items: center; /* justify-items + align-items (grid) */
/* สำหรับ flex ใช้แยกกัน */
}
คำแนะนำ
- ค่าเริ่มต้น
stretch ทำให้ items ยืดเต็ม cross axis - ต้องระวังถ้า items มี height คงที่
- ใช้
align-items: center ร่วม justify-content: center เพื่อจัดกึ่งกลางทั้ง 2 แกน
- สำหรับ multi-line ให้ใช้
align-content ควบคุมบรรทัด แทน align-items
- ใช้
align-self บน item เดียวที่ต้องการจัดต่างจากกลุ่ม