Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

จัดตำแหน่ง Flex Items แนวนอนด้วย justify-content


justify-content สำหรับการจัดแนวนอน

คุณสมบัติ justify-content ควบคุมการกระจายพื้นที่ว่างบน Main Axis เมื่อ flex items ไม่ใช้พื้นที่ทั้งหมด สำหรับ flex-direction: row (default) จะควบคุมการจัด แนวนอน

ตัวอย่าง: justify-content: center

<!DOCTYPE html>
<html>
<head>
  <style>
    .mycontainer {
      display: flex;
      background-color: #e3f2fd;
      justify-content: center;     /* จัดกึ่งกลางแนวนอน */
      padding: 20px;
      gap: 10px;
    }
    .mycontainer > div {
      background-color: white;
      border: 2px solid #2196f3;
      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: row)

ค่า ผลลัพธ์ ใช้เมื่อไหร่
flex-start (default) Items ชิดซ้าย เริ่มต้นปกติ, Reading flow
flex-end Items ชิดขวา RTL, Action buttons ทางขวา
center Items กึ่งกลาง Hero, Modal, Pagination
space-between Item แรกชิดซ้าย ตัวสุดท้ายชิดขวา กระจายกลาง Navbar, Header, Card footer
space-around พื้นที่รอบ items เท่าๆ กัน (ขอบ = 0.5x) Card grid, Gallery
space-evenly พื้นที่ทุกช่องเท่าๆ กัน (ขอบ = 1x) Equal spacing grid

การใช้งานจริง: Navbar Pattern

.navbar {
  display: flex;
  justify-content: space-between;  /* Brand ซ้าย, Menu ขวา */
  align-items: center;
  padding: 16px 24px;
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.nav-brand {
  font-weight: 700;
  font-size: 1.25rem;
}

.nav-menu {
  display: flex;
  gap: 24px;
  list-style: none;
}

.nav-actions {
  display: flex;
  gap: 12px;
}

การใช้งานจริง: Pagination

.pagination {
  display: flex;
  justify-content: center;   /* กึ่งกลาง */
  gap: 8px;
  padding: 16px;
}

.page-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: white;
  cursor: pointer;
}

.page-btn.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

Modern Approach: gap + margin-auto

.flex-container {
  display: flex;
  gap: 16px;  /* ระยะห่างอัตโนมัติ */
}

.push-right {
  margin-left: auto;  /* ดัน item นี้ไปขวาสุด */
}

.push-left {
  margin-right: auto; /* ดัน item นี้ไปซ้ายสุด */
}

คำแนะนำ

  • ใช้ gap แทน margin ระหว่าง items (cleaner, ไม่มี margin collapsing issues)
  • space-between เหมาะสำหรับ Navbar (Logo ซ้าย, Actions ขวา)
  • center เหมาะสำหรับ Hero, Modal, Loading states
  • จำไว้: Main Axis ขึ้นอยู่กับ flex-direction (row=horizontal, column=vertical)