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

วิธีสร้าง Mixed Column Layout Grid ด้วย CSS

Mixed Column Layout คือ Grid ที่จำนวนคอลัมน์เปลี่ยนไปตามขนาดหน้าจอ: 4 คอลัมน์บนเดสก์ท็อป → 2 คอลัมน์บนแท็บเล็ต → 1 คอลัมน์บนมือถือ ตัวอย่างนี้ใช้ Float + Multiple Media Queries

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

<!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; }
    * { box-sizing: border-box; }
    .col {
      color: white;
      float: left;
      width: 25%;
      padding: 10px;
    }
    .colContainer:after {
      content: "";
      display: table;
      clear: both;
    }
    @media screen and (max-width: 900px) {
      .col { width: 50%; }
    }
    @media screen and (max-width: 600px) {
      .col { width: 100%; }
    }
  </style>
</head>
<body>
  <h1>Mixed col Layout Example</h1>
  <h2>Resize the screen to see the below divs resize themselves</h2>
  <div class="colContainer">
    <div class="col" style="background-color:rgb(153, 29, 224);"><h2>First col</h2></div>
    <div class="col" style="background-color:rgb(12, 126, 120);"><h2>Second col</h2></div>
    <div class="col" style="background-color:rgb(207, 41, 91);"><h2>Third col</h2></div>
    <div class="col" style="background-color:rgb(204, 91, 39);"><h2>Fourth col</h2></div>
  </div>
</body>
</html>

Breakpoints ในตัวอย่าง

Screen WidthColumnsColumn Width
> 900px425%
600px - 900px250%
≤ 600px1100%

Modern Approach: CSS Grid (One-Liner)

.colContainer {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  padding: 20px;
}
/* 
  auto-fit + minmax = Responsive ทันที ไม่ต้อง Media Query!
  - minmax(200px, 1fr): คอลัมน์ขั้นต่ำ 200px สูงสุด 1fr (แบ่งพื้นที่เท่าๆ กัน)
  - เมื่อจอเล็กลง คอลัมน์จะหลุดบรรทัดใหม่เอง
*/

Flexbox Alternative

.colContainer {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.col {
  flex: 1 1 200px; /* Grow | Shrink | Basis */
  min-width: 200px;
}

Advanced: Container Queries (CSS สายใหม่)

.colContainer {
  container-type: inline-size;
}
@container (min-width: 800px) {
  .col { /* 4 columns styles */ }
}
@container (min-width: 500px) {
  .col { /* 2 columns styles */ }
}
/* Layout ปรับตามขนาด Container ไม่ใช่ Viewport */

Comparison: Float vs Grid vs Flexbox

FeatureFloat (เก่า)FlexboxGrid (แนะนำ)
Code Complexityสูง (Clearfix, Calc)ปานกลางต่ำ (1-2 บรรทัด)
ResponsiveMedia Query Manualauto-fit/flex-wrapauto-fit/minmax
Alignment Controlยากดีมากดีที่สุด
Gap Supportไม่มี (ต้อง用 Margin)มี gapมี gap
Browser Supportทุกตัว (IE6+)IE10+Modern (Edge 16+)

เมื่อไหร่ควรใช้แต่ละอย่าง

  • Grid: 2D Layout (Rows + Columns), Card Grids, Page Layouts
  • Flexbox: 1D Layout (Row หรือ Column), Navigation, Centering, Card Internals
  • Float: Text Wrapping รอบรูปภาพ, Legacy Support เท่านั้น