flex-direction คืออะไร?
คุณสมบัติ flex-direction กำหนด ทิศทาง (Direction) ของ Main Axis ซึ่งควบคุมว่า flex items จะเรียงตัวอย่างไร: แนวนอน (Row) หรือแนวตั้ง (Column) และลำดับปกติหรือกลับ
ค่าทั้ง 4 ค่า
| ค่า | Main Axis | ลำดับ | Cross Axis |
|---|---|---|---|
row (default) |
แนวนอน (Horizontal) | ซ้าย → ขวา | แนวตั้ง (บน → ล่าง) |
row-reverse |
แนวนอน | ขวา → ซ้าย | แนวตั้ง (บน → ล่าง) |
column |
แนวตั้ง (Vertical) | บน → ล่าง | แนวนอน (ซ้าย → ขวา) |
column-reverse |
แนวตั้ง | ล่าง → บน | แนวนอน (ซ้าย → ขวา) |
ตัวอย่าง: flex-direction: column (แนวตั้ง)
<!DOCTYPE html>
<html>
<head>
<style>
.mycontainer {
display: flex;
flex-direction: column; /* เรียงจากบนลงล่าง */
background-color: #fff3e0;
padding: 10px;
gap: 10px;
}
.mycontainer > div {
background-color: white;
border: 2px solid #ff9800;
text-align: center;
line-height: 50px;
font-size: 20px;
width: 100%;
max-width: 300px;
border-radius: 4px;
}
</style>
</head>
<body>
<h1>ตัวอย่าง flex-direction: column</h1>
<div class="mycontainer">
<div>Q1</div>
<div>Q2</div>
<div>Q3</div>
<div>Q4</div>
<div>Q5</div>
<div>Q6</div>
</div>
</body>
</html>
ตัวอย่าง: flex-direction: row-reverse
.reverse-row {
display: flex;
flex-direction: row-reverse; /* เรียงจากขวาไปซ้าย */
gap: 10px;
}
/* ใช้สำหรับ RTL languages หรือ UI ที่ต้องการลำดับกลับ */
.navbar-rtl {
flex-direction: row-reverse;
}
ผลกระทบต่อ justify-content และ align-items
.container {
display: flex;
flex-direction: column; /* Main Axis = Vertical */
/* justify-content ควบคุมแนวตั้ง (Main Axis) */
justify-content: center; /* จัดกึ่งกลางแนวตั้ง */
justify-content: space-between; /* กระจายแนวตั้ง */
/* align-items ควบคุมแนวนอน (Cross Axis) */
align-items: center; /* จัดกึ่งกลางแนวนอน */
align-items: stretch; /* ยืดเต็มความกว้าง (default) */
}
Shorthand: flex-flow
/* รวม flex-direction + flex-wrap */
flex-flow: row wrap; /* default */
flex-flow: column wrap;
flex-flow: row-reverse wrap-reverse;
กรณีการใช้งานจริง
- Column: Mobile layout, Form fields, Sidebar navigation, Stack cards
- Row: Navigation bar, Horizontal card grid, Toolbar
- Row-reverse: RTL languages, "Back" button ทางซ้าย, Chat bubbles (me)
- Column-reverse: Chat log (ใหม่สุดอยู่บน), Notification stack
Responsive Pattern
.responsive-container {
display: flex;
flex-direction: column; /* Mobile: stack แนวตั้ง */
gap: 16px;
}
@media (min-width: 768px) {
.responsive-container {
flex-direction: row; /* Desktop: จัดติดกันแนวนอน */
align-items: center;
}
}
คำแนะนำ
- ค่าเริ่มต้นคือ
row(แนวนอน ซ้าย→ขวา) - เมื่อเปลี่ยน direction justify-content และ align-items จะสลับบทบาทกัน
- ใช้
gapแทน margin สำหรับระยะห่างระหว่าง items - รวมกับ
flex-wrapผ่านflex-flowเพื่อเขียนสั้นลง