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

การเปลี่ยนเลย์เอาต์ตามขนาดหน้าจอด้วย CSS (Responsive Layout)

Responsive Layout: เปลี่ยนจำนวนคอลัมน์ตาม Breakpoint ด้วย Media Query

ใช้ float + width% + @media query ทำให้คอลัมน์ 4 คอลัมน์บน Desktop กลาย 2 คอลัมน์บน Tablet และ 1 คอลัมน์บน Mobile

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

<!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>เปลี่ยนเลย์เอาต์ตามขนาดหน้าจอ</h1>
  <h2>Resize หน้าจอเพื่อดูคอลัมน์ปรับตัว</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>

แนวทางทันสมัย: Flexbox/Grid (แนะนำ)

/* Flexbox */
.container { display: flex; flex-wrap: wrap; gap: 20px; }
.col { flex: 1 1 200px; } /* ขยายได้ หดได้ ขั้นต่ำ 200px */

/* Grid - ทรงพลังที่สุด */
.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

Grid auto-fit + minmax ทำ responsive อัตโนมัติ ไม่ต้องเขียน media query หลาย breakpoint

Breakpoint แนะนำ (Mobile First)

  • @media (min-width: 576px) – Small (landscape phone)
  • @media (min-width: 768px) – Medium (tablet)
  • @media (min-width: 992px) – Large (desktop)
  • @media (min-width: 1200px) – XL (large desktop)