ใน Flexbox ใช้คุณสมบัติ justify-content: center เพื่อจัดให้ flex items อยู่กึ่งกลางตาม main axis (แนวนอนโดยปกติ)
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head>
<style>
.mycontainer {
display: flex;
background-color: red;
justify-content: center;
}
.mycontainer > div {
background-color: #F1C40F;
text-align: center;
line-height: 60px;
font-size: 30px;
width: 100px;
margin: 5px;
}
</style>
</head>
<body>
<h1>Quiz</h1>
<div class="mycontainer">
<div>Q1</div>
<div>Q2</div>
<div>Q3</div>
<div>Q4</div>
</div>
</body>
</html>
ค่าอื่นๆ ของ justify-content:
flex-start(default): ชิดจุดเริ่มต้นflex-end: ชิดจุดสิ้นสุดspace-between: กระจายเท่าๆ กัน ชิดปลายทั้งสองข้างspace-around: กระจายเท่าๆ กัน มีระยะห่างรอบๆ itemspace-evenly: กระจายเท่าๆ กัน ระยะห่างเท่ากันทุกช่อง
หมายเหตุ: หาก flex-direction: column แล้ว main axis จะเป็นแนวตั้ง ใช้ align-items: center เพื่อจัดกึ่งกลางแนวนอน (cross axis) แทน