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

คุณสมบัติ align-items: stretch ใน CSS Flexbox


align-items: stretch คืออะไร?

ค่า stretch เป็น ค่าเริ่มต้น (default) ของ align-items ทำให้ flex items ยืดเต็มความสูง (Cross Axis) ของคอนเทนเนอร์ โดยอัตโนมัติ (ถ้า item ไม่มี height คงที่)

เงื่อนไขการทำงาน

  • Item ไม่มี height คงที่ (หรือ height: auto)
  • Item ไม่มี align-self ที่ทับซ้อน
  • Cross Axis มีขนาดจำกัด (container มี height หรือ items มีความสูงไม่เท่ากัน)

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

<!DOCTYPE html>
<html>
<head>
  <style>
    .mycontainer {
      display: flex;
      height: 200px;                 /* ความสูงจำกัด */
      background-color: #ffebee;
      align-items: stretch;          /* ค่าเริ่มต้น - ยืดเต็มความสูง */
    }
    .mycontainer > div {
      background-color: #ff9800;
      color: white;
      text-align: center;
      line-height: 60px;             /* สำหรับจัดข้อความกึ่งกลางแนวตั้ง */
      font-size: 24px;
      width: 100px;
      margin: 5px;
      border-radius: 4px;
      /* ไม่มี height -> จะยืดเต็ม 200px */
    }
  </style>
</head>
<body>
  <h1>ตัวอย่าง align-items: stretch (default)</h1>
  <p>Items ทุกตัวจะยืดสูงเท่ากับ container (200px) อัตโนมัติ</p>
  <div class="mycontainer">
    <div>Q1</div>
    <div>Q2</div>
    <div>Q3</div>
    <div>Q4</div>
  </div>
</body>
</html>

เปรียบเทียบ: stretch vs center vs flex-start

.container {
  display: flex;
  height: 200px;
}

.stretch-items   { align-items: stretch; }   /* default - ยืดเต็ม */
.center-items    { align-items: center; }    /* กึ่งกลางแนวตั้ง */
.start-items     { align-items: flex-start; }/* ชิดบน */
.end-items       { align-items: flex-end; }  /* ชิดล่าง */
.baseline-items  { align-items: baseline; }  /* จัด baseline */

กรณีที่ stretch ไม่ทำงาน

กรณี เหตุผล แก้ไข
Item มี height: 100px ความสูงถูกล็อกไว้แล้ว ลบ height หรือใช้ min-height
Item มี align-self: center Override ด้วย align-self ลบ align-self หรือตั้งค่า stretch
Container ไม่มีความสูง ไม่มีขนาดอ้างอิงให้ยืด เพิ่ม height/min-height ให้ container
flex-direction: column Cross Axis = Horizontal, stretch = ยืดกว้าง ทำงานปกติ แต่เป็นแนวนอน

การใช้งานจริง: Equal Height Cards

.card-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  align-items: stretch;  /* default - cards สูงเท่ากัน */
}

.card {
  flex: 1 1 300px;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow: hidden;
}

.card-content {
  flex: 1;          /* เนื้อหาขยายเต็ม */
  padding: 24px;
}

.card-footer {
  padding: 16px 24px;
  border-top: 1px solid #eee;
}

/* ทุก card จะสูงเท่ากัน เพราะ align-items: stretch (default) */

คำแนะนำ

  • stretch เป็นค่าเริ่มต้น - ไม่ต้องเขียนก็ได้ ถ้าต้องการพฤติกรรมนี้
  • หากไม่ต้องการยืด ให้ตั้งค่า align-items: flex-start หรือ center
  • สำหรับ Card grid ให้ใช้ align-items: stretch ร่วมกับ nested flex column เพื่อ Equal height
  • ใช้ align-self บน item เดียวที่ต้องการพฤติกรรมต่างจากกลุ่ม