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

จัดเรียง Flex Items ตาม Cross Axis ด้วย CSS3 (Align-items)

Align-items: จัดตำแหน่ง Flex Items ตาม Cross Axis (แนวตั้งใน Row direction)

ใน Flex container แนวหลัก (main axis) default คือ row (ซ้าย→ขวา) Cross axis คือแนวตั้ง ใช้ align-items จัด item ตาม cross axis

โค้ดตัวอย่าง

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .container {
      height: 200px; display: flex; width: 100%;
      align-items: center; /* จุดสำคัญ: จัดกึ่งกลางแนวตั้ง */
      border: 2px solid red;
    }
    div { width: 100px; height: 100px; color: white; text-align: center; font-size: 30px; }
    .first { background-color: rgb(55, 0, 255); }
    .second { background-color: red; }
    .third { background-color: rgb(140, 0, 255); }
  </style>
</head>
<body>
  <h1>Align Flex Items Along Cross Axis</h1>
  <div class="container">
    <div class="first">First Div</div>
    <div class="second">Second Div</div>
    <div class="third">Third Div</div>
  </div>
</body>
</html>

Align-items Values

Valueผลลัพธ์ (Row direction)
stretch (default)ยืดเต็มความสูง container
flex-startชิดบน
flex-endชิดล่าง
centerกึ่งกลางแนวตั้ง
baselineจัดตาม baseline ของข้อความ

Align-self: Override ต่อ Item

.special-item { align-self: flex-end; } /* item นี้ชิดล่างคนเดียว */

Column Direction

ถ้า flex-direction: column Main axis = แนวตั้ง, Cross axis = แนวนอน align-items จะจัดแนวนอนแทน (เหมือน justify-content ใน row)