flex-direction สำหรับกำหนดทิศทาง
คุณสมบัติ flex-direction ระบุทิศทางของ Main Axis ซึ่งกำหนดว่า flex items จะเรียงตัวอย่างไร: แนวนอน (row) หรือแนวตั้ง (column) และลำดับปกติหรือกลับ
ค่าทั้ง 4 ค่า
| ค่า | ทิศทาง | Main Axis | Cross Axis |
|---|---|---|---|
row (default) |
ซ้าย → ขวา | Horizontal | Vertical |
row-reverse |
ขวา → ซ้าย | Horizontal | Vertical |
column |
บน → ล่าง | Vertical | Horizontal |
column-reverse |
ล่าง → บน | Vertical | Horizontal |
ตัวอย่าง: 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>
<p>Items เรียงจากบนลงล่าง: Q1, Q2, Q3, Q4, Q5, Q6</p>
<div class="mycontainer">
<div>Q1</div>
<div>Q2</div>
<div>Q3</div>
<div>Q4</div>
<div>Q5</div>
<div>Q6</div>
</div>
</body>
</html>
ผลกระทบต่อ justify-content และ align-items
/* flex-direction: row (default) */
.row-container {
display: flex;
flex-direction: row;
justify-content: center; /* จัดกึ่งกลาง "แนวนอน" */
align-items: center; /* จัดกึ่งกลาง "แนวตั้ง" */
}
/* flex-direction: column */
.column-container {
display: flex;
flex-direction: column;
justify-content: center; /* จัดกึ่งกลาง "แนวตั้ง" */
align-items: center; /* จัดกึ่งกลาง "แนวนอน" */
}
การใช้งานจริง: Mobile-First Responsive
.container {
display: flex;
flex-direction: column; /* Mobile: stack แนวตั้ง */
gap: 16px;
}
@media (min-width: 768px) {
.container {
flex-direction: row; /* Desktop: จัดแนวนอน */
}
}
/* หรือใช้ container queries (modern) */
@container (min-width: 600px) {
.container {
flex-direction: row;
}
}
Shorthand: flex-flow
/* รวม flex-direction + flex-wrap */
flex-flow: row wrap; /* แนวนอน + wrap */
flex-flow: column wrap; /* แนวตั้ง + wrap */
flex-flow: row-reverse wrap-reverse;
คำแนะนำ
- ค่าเริ่มต้นคือ
row(แนวนอน ซ้าย→ขวา) - ใช้
columnสำหรับ Form, Sidebar, Page layout, Mobile stacking - เมื่อเปลี่ยน direction ให้จำว่า justify-content และ align-items จะสลับบทบาท
- ใช้
gapสำหรับระยะห่างระหว่าง items - สำหรับ RTL ให้ใช้
dir="rtl"บน HTML tag แทนการเปลี่ยน flex-direction