justify-content คืออะไร?
คุณสมบัติ justify-content ควบคุมการจัดเรียง flex items บน Main Axis (แกนหลัก) เมื่อ items ไม่ใช้พื้นที่ทั้งหมด ใช้สำหรับจัดชิดซ้าย ชิดขวา กึ่งกลาง หรือกระจายพื้นที่ว่าง
ค่าทั้งหมด (7 ค่า)
| ค่า |
พฤติกรรม |
เหมาะสำหรับ |
flex-start (default) |
ชิดจุดเริ่มต้น (ซ้ายสำหรับ row) |
เริ่มต้นปกติ, Text alignment |
flex-end |
ชิดจุดสิ้นสุด (ขวาสำหรับ row) |
Align items ขวา |
center |
กึ่งกลาง Main Axis |
จัดกึ่งกลาง, Modal, Hero |
space-between |
item แรกชิดเริ่มต้น ตัวสุดท้ายชิดสิ้นสุด กระจายกลางเท่าๆ กัน |
Navbar, Toolbar, Card footer |
space-around |
พื้นที่รอบ item เท่าๆ กัน (ขอบ = 0.5x ช่องว่างกลาง) |
Card grid, Gallery |
space-evenly |
พื้นที่ทุกช่องเท่าๆ กันหมด (รวมขอบ = ช่องว่างกลาง) |
Grid สม่ำเสมอ, Modern layout |
ตัวอย่าง: justify-content: center
<!DOCTYPE html>
<html>
<head>
<style>
.mycontainer {
display: flex;
background-color: #fff3e0;
justify-content: center; /* จัดกึ่งกลาง Main Axis */
padding: 20px;
gap: 10px;
}
.mycontainer > div {
background-color: white;
border: 2px solid #ff9800;
text-align: center;
line-height: 50px;
font-size: 20px;
width: 100px;
border-radius: 4px;
}
</style>
</head>
<body>
<h1>ตัวอย่าง justify-content: center</h1>
<div class="mycontainer">
<div>Q1</div>
<div>Q2</div>
<div>Q3</div>
<div>Q4</div>
</div>
</body>
</html>
ผลกระทบของ flex-direction ต่อ justify-content
| flex-direction |
Main Axis |
justify-content: center |
| row (default) |
แนวนอน (ซ้าย→ขวา) |
จัดกึ่งกลางแนวนอน |
| row-reverse |
แนวนอน (ขวา→ซ้าย) |
จัดกึ่งกลางแนวนอน (ลำดับกลับ) |
| column |
แนวตั้ง (บน→ล่าง) |
จัดกึ่งกลางแนวตั้ง |
| column-reverse |
แนวตั้ง (ล่าง→บน) |
จัดกึ่งกลางแนวตั้ง (ลำดับกลับ) |
การใช้งานจริง: Navigation Bar
.navbar {
display: flex;
justify-content: space-between; /* Logo ซ้าย, Menu ขวา */
align-items: center;
padding: 16px 24px;
}
.nav-links {
display: flex;
gap: 32px;
}
.nav-actions {
display: flex;
gap: 16px;
}
การใช้งานจริง: Card Actions
.card-footer {
display: flex;
justify-content: flex-end; /* ปุ่มชิดขวา */
gap: 8px;
padding: 16px;
border-top: 1px solid #eee;
}
.card-footer .btn-primary {
margin-left: auto; /* ถ้าอยากให้ปุ่มหลักชิดขวาสุด ส่วนอื่นชิดซ้าย */
}
Modern Alternative: gap + margin-auto
.modern-container {
display: flex;
gap: 16px; /* ระยะห่างอัตโนมัติ */
}
.push-to-end {
margin-left: auto; /* ดัน item นี้ไปขวาสุด */
}
คำแนะนำ
- ใช้
gap แทน margin ระหว่าง items (รองรับดีในเบราวเซอร์ใหม่)
space-between สำหรับ Navbar (Logo ซ้าย, Menu ขวา)
center สำหรับ Hero section, Modal, Loading spinner
space-around หรือ space-evenly สำหรับ Grid cards
- จำไว้: justify-content ทำงานบน Main Axis ซึ่งขึ้นอยู่กับ flex-direction