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

คุณสมบัติ flex-flow ใน CSS Flexbox (Shorthand)


flex-flow คืออะไร?

คุณสมบัติ flex-flow เป็น shorthand property ที่รวม flex-direction และ flex-wrap ไว้ในบรรทัดเดียว ช่วยเขียนโค้ดสั้นลงและอ่านง่ายขึ้น

ไวยากรณ์

flex-flow:  ;

/* ค่าเริ่มต้น */
flex-flow: row nowrap;

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<head>
  <style>
    .mycontainer {
      display: flex;
      background-color: #fff3e0;
      flex-flow: column wrap;    /* shorthand: direction + wrap */
      padding: 10px;
      gap: 10px;
      height: 300px;             /* ต้องมีความสูงเพื่อให้ wrap ทำงานชัดเจน */
    }
    .mycontainer > div {
      background-color: white;
      border: 2px solid #ff9800;
      text-align: center;
      line-height: 40px;
      font-size: 20px;
      width: 100px;
      border-radius: 4px;
    }
  </style>
</head>
<body>
  <h1>ตัวอย่าง flex-flow: column wrap</h1>
  <p>Items เรียงแนวตั้ง (column) และขึ้นคอลัมน์ใหม่ (wrap) เมื่อไม่พอพื้นที่</p>
  <div class="mycontainer">
    <div>Q1</div>
    <div>Q2</div>
    <div>Q3</div>
    <div>Q4</div>
    <div>Q5</div>
    <div>Q6</div>
    <div>Q7</div>
    <div>Q8</div>
    <div>Q9</div>
  </div>
</body>
</html>

การรวมค่าที่พบบ่อย (Common Combinations)

flex-flow flex-direction flex-wrap ใช้เมื่อไหร่
row wrap row wrap Responsive card grid, Navbar ที่ wrap บนมือถือ
column wrap column wrap Masonry layout, Vertical list ที่ wrap เป็นคอลัมน์
row nowrap row nowrap Default - single line horizontal
column nowrap column nowrap Form, Sidebar, Full-height layout
row-reverse wrap row-reverse wrap RTL layouts, Chat bubbles (me)
column-reverse wrap column-reverse wrap Chat log (newest top), Notifications

ตัวอย่าง: Responsive Card Grid

.card-grid {
  display: flex;
  flex-flow: row wrap;           /* แนวนอน + wrap */
  gap: 24px;
  padding: 24px;
  justify-content: space-between; /* หรือ center, flex-start */
}

.card {
  flex: 1 1 300px;               /* min 300px, ขยายเท่ากัน */
  max-width: 100%;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* บนมือถือ: flex-basis 300px ทำให้เหลือ 1 คอลัมน์
   บนแท็บเล็ต: 2 คอลัมน์
   บนเดสก์ทอป: 3-4 คอลัมน์ */

ตัวอย่าง: Masonry-style với column wrap

.masonry {
  display: flex;
  flex-flow: column wrap;      /* แนวตั้ง + wrap */
  height: 800px;               /* ต้องมีความสูงจำกัด */
  gap: 16px;
  padding: 16px;
}

.masonry-item {
  width: 200px;                /* ความกว้างคงที่ */
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* Items จะไหล: ลงบน → ขึ้นคอลัมน์ใหม่ขวา → ลงบน... */

คำแนะนำ

  • ใช้ flex-flow แทนการเขียน flex-direction และ flex-wrap แยกกัน
  • ค่าเริ่มต้น row nowrap - สามารถละเว้นได้ถ้าใช้ค่าเริ่มต้น
  • column wrap ต้องมี ความสูงจำกัด (height/max-height) ของคอนเทนเนอร์
  • ร่วมกับ gap สำหรับระยะห่างที่สม่ำเสมอ