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

คุณสมบัติ align-self ใน CSS Flexbox


align-self คืออะไร?

คุณสมบัติ align-self ใช้สำหรับ override การจัดตำแหน่ง Cross Axis ของ flex item เดียว โดยไม่กระทบ items อื่นๆ ในคอนเทนเนอร์เดียวกัน ทับซ้อนค่า align-items ของคอนเทนเนอร์

ค่าที่ใช้ได้

  • auto (default) - 繼承จาก align-items ของคอนเทนเนอร์
  • flex-start - ชิดจุดเริ่มต้น Cross Axis
  • flex-end - ชิดจุดสิ้นสุด Cross Axis
  • center - กึ่งกลาง Cross Axis
  • baseline - จัดตาม baseline ของข้อความ
  • stretch - ยืดเต็มความสูง Cross Axis (ถ้าไม่มี height)

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

<!DOCTYPE html>
<html>
<head>
  <style>
    .mycontainer {
      display: flex;
      height: 300px;
      background-color: #fff3e0;
      /* align-items: stretch (default) - items จะยืดสูง 300px */
    }
    .mycontainer > div {
      background-color: white;
      border: 2px solid #ff9800;
      text-align: center;
      line-height: 80px;
      font-size: 32px;
      width: 100px;
      margin: 10px;
      border-radius: 4px;
    }
    /* Q4 จะอยู่กึ่งกลางแนวตั้ง แทนที่จะยืดเต็มความสูง */
    .centered {
      align-self: center;
      background-color: #4CAF50;
      color: white;
    }
  </style>
</head>
<body>
  <h1>ตัวอย่าง align-self: center</h1>
  <p>Q1-Q3 และ Q5 ยืดเต็มความสูง (align-items: stretch) แต่ Q4 อยู่กึ่งกลาง</p>
  <div class="mycontainer">
    <div>Q1</div>
    <div>Q2</div>
    <div>Q3</div>
    <div class="centered">Q4 (center)</div>
    <div>Q5</div>
  </div>
</body>
</html>

ตัวอย่างครบ: align-self ทุกค่า

.container {
  display: flex;
  height: 200px;
  background: #f5f5f5;
  align-items: stretch;  /* default */
}

.item-start    { align-self: flex-start; background: #ffcdd2; }
.item-end      { align-self: flex-end;   background: #c8e6c9; }
.item-center   { align-self: center;     background: #bbdefb; }
.item-baseline { align-self: baseline;   background: #ffe0b2; }
.item-stretch  { align-self: stretch;    background: #e1bee7; }

align-self vs align-items

คุณสมบัติ ระดับ ผลกระทบ
align-items Container (Parent) Items ทั้งหมดในคอนเทนเนอร์
align-self Item (Child) เฉพาะ item นั้นๆ

กรณีการใช้งานจริง

  • ปุ่ม "Primary Action" ใน Card: ให้ปุ่มอยู่กึ่งกลางแนวตั้ง ขณะข้อความอื่นๆ ยืดเต็ม
  • Icon ใน List Item: ให้ icon อยู่กึ่งกลางแนวตั้ง ขณะข้อความหลายบรรทัด
  • Form Input + Label: จัด label ให้ตรงกลางกับ input field

ตัวอย่าง: Card กับปุ่มกึ่งกลาง

.card {
  display: flex;
  flex-direction: column;
  height: 300px;
}

.card-content {
  flex: 1;  /* ยืดเต็มพื้นที่ */
}

.card-action {
  align-self: center;  /* ปุ่มอยู่กึ่งกลางแนวนอน */
  margin-top: auto;    /* หรือใช้ margin-top: auto เพื่อผลลัพธ์คล้ายกัน */
}

คำแนะนำ

  • ใช้ align-self เมื่อต้องการจัดตำแหน่ง item เดียวต่างจากกลุ่ม
  • ถ้า container มี align-items: stretch ให้ item ที่ไม่ต้องการยืด ต้องกำหนด align-self อื่น หรือกำหนด height คงที่
  • รองรับในทุกเบราวเซอร์สมัยใหม่ (IE10+)