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

วิธีสร้างคอลัมน์สูงเท่ากัน (Equal Height Columns) ด้วย CSS

ใช้ display: table และ table-cell ทำคอลัมน์เท่าสูง

วิธีคลาสสิกก่อนยุค Flexbox/Grid ใช้ display: table บน container และ display: table-cell บนคอลัมน์ ทำให้คอลัมน์ทุกตัวสูงเท่ากันอัตโนมัติ ไม่ต้องกำหนดความสูงคงที่

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

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .container {
      display: table;
      width: 100%;
    }
    .column {
      display: table-cell;
      padding: 16px;
      background-color: greenyellow;
    }
    .column:nth-of-type(2n-1) {
      color: red;
      background-color: yellow;
    }
  </style>
</head>
<body>
  <h1>ตัวอย่าง Equal Height Columns</h1>
  <div class="container">
    <div class="column"><h2>Column 1</h2><h2>Column 1</h2><h2>Column 1</h2></div>
    <div class="column"><h2>Column 2</h2><h2>Column 2</h2><h2>Column 2</h2></div>
    <div class="column"><h2>Column 3</h2><h2>Column 3</h2><h2>Column 3</h2></div>
  </div>
</body>
</html>

วิธีทันสมัย (แนะนำ)

ปัจจุบันควรใช้ Flexbox หรือ CSS Grid ซึ่งง่ายและยืดหยุ่นกว่า:

  • Flexbox: .container { display: flex; } – คอลัมน์จะเท่าสูงอัตโนมัติ (default align-items: stretch)
  • Grid: .container { display: grid; grid-template-columns: repeat(3, 1fr); }

ทั้งสองวิธีรองรับ responsive, gap, และจัดเรียงลำดับได้ง่ายกว่า table-cell มาก